I want to create a custom baseline for TextFormField in Flutter. The example for what I wanna do is given below.
You can create your custom input border which would extend UnderlineInputBorder. What you need to override is the paint method.
I implemented here in this manner so that you can easily add colors and it would then draw lines for you giving same width to each color, but feel free to update it for your needs.
That would be something like this:
class CustomInputBorder extends UnderlineInputBorder {
#override
void paint(Canvas canvas, Rect rect,
{double gapStart,
double gapExtent = 0.0,
double gapPercentage = 0.0,
TextDirection textDirection}) {
drawLines(
canvas, rect, [Colors.red, Colors.green, Colors.blue, Colors.orange]);
}
void drawLines(Canvas canvas, Rect rect, List<Color> colors) {
var borderWidth = rect.bottomRight.dx - rect.bottomLeft.dx;
var sectionWidth = borderWidth / colors.length;
var startingPoint = rect.bottomLeft;
var endPoint = getEndPoint(startingPoint, sectionWidth);
colors.forEach((color) {
var paint = Paint();
paint.color = color;
paint.strokeWidth = 1.0;
canvas.drawLine(startingPoint, endPoint, paint);
startingPoint = getNewStartingPoint(startingPoint, sectionWidth);
endPoint = getEndPoint(startingPoint, sectionWidth);
});
}
Offset getNewStartingPoint(Offset oldStartingPoint, double width) {
return Offset(oldStartingPoint.dx + width, oldStartingPoint.dy);
}
Offset getEndPoint(Offset startingPoint, double width) {
return Offset(startingPoint.dx + width, startingPoint.dy);
}
}
And then you can use it:
TextField(
decoration: InputDecoration(
labelText: 'Username',
border: CustomInputBorder(),
enabledBorder: CustomInputBorder(),
focusedBorder: CustomInputBorder(),
),
),
This is how it looks like right now:
https://i.stack.imgur.com/fDTBu.png
https://i.stack.imgur.com/z4SjM.png
https://i.stack.imgur.com/l5aW8.png
First place worth looking at is the UnderlineInputBorder class. You should be able to set the decoration: of a TextFormField as an InputDecoration, which can take an UnderlineInputBorder as its border:. You should then be able to style the border's `BorderSide' property appropriately to match your design.
Related
I search a lot how to apply frame on images but found no answer. I read stack function in which we can put an image inside other but its not good trick. I think there must be library for frame and by using that frame can automatically apply on border of image. Please guide me how can I use different design of frame outside image like some filters application.
I want to give options of frame to user like below and when user click on any frame that will apply on image
There are many approaches for that issue. I've used several in the past. It strongly differs in the way you want to make use of the image. Do you need to paint something on the image or just display it?
In my opinion multiple frames on an image can be achieved best with CustomPainter. Check out the documentation for more. The following Painter should do the trick.
class TestPainter extends CustomPainter {
final ui.Image image;
TestPainter({required this.image});
#override
void paint(Canvas canvas, Size size) {
//draw the image
canvas.drawImage(image, const Offset(0, 0), Paint());
double rectWidth = image.width.toDouble();
double rectHeight = image.height.toDouble();
final imageCenter = Offset(image.width / 2, image.height / 2);
//first frame
var border1 = Rect.fromCenter(
center: imageCenter,
width: rectWidth + 1,
height: rectHeight + 1);
var painting = Paint();
painting.color = Colors.red;
painting.strokeWidth = 2;
painting.style = PaintingStyle.stroke;
canvas.drawRect(border1, painting);
//second frame
var border2 = Rect.fromCenter(
center: imageCenter,
width: rectWidth + 3,
height: rectHeight + 3);
var painting2 = Paint();
painting2.color = Colors.green;
painting2.strokeWidth = 2;
painting2.style = PaintingStyle.stroke;
canvas.drawRect(
border2,
painting2,
);
}
#override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
Please be cautious. The Image in that example needs to be an Image of the dart:ui library (Documentation). There are various way to convert. Depends on your project.
This sketch shows what the final result should look like:
A CustomPainter fills its Canvas (yellow area) with a slightly translucent background color. (Amber with an opacity of 0.8 in the sketch).
The CustomPainter draws a rectangle onto the canvas. And here it's getting interesting: The rectangle should only change the alpha value of the background color drawn at the previous step. The idea is to highlight some points of interest, by fading some "holes" in and out (visualized by the smaller, darker rectangle inside the yellow rectangle in the sketch above).
In code it looks simple:
class Highlighter extends CustomPainter {
ValueListenable<double> valueListenable;
Color backgroundColor;
Highlighter({required this.valueListenable, this.backgroundColor = Colors.amber}) : super(repaint: valueListenable);
#override
void paint(Canvas canvas, Size size) {
Color colorHole = backgroundColor.withOpacity(0.40);
Paint holePainter = Paint();
holePainter.color = colorHole;
holePainter.blendMode = BlendMode.dstOut;
canvas.saveLayer(null, holePainter);
// Step 1: Draw the background:
canvas.drawColor(backgroundColor.withOpacity(0.80), BlendMode.srcOver);
// Step 2: Highlight a rectangle:
canvas.drawRect(const Rect.fromLTWH(100, 100, 100, 100), holePainter);
canvas.restore();
}
#override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
Problem is, the colors ain't right:
canvas.DrawColor() draws some shade of gray instead of Amber, although the holes appear to be ok.
Removing the saveLayer()/restore() calls draws the background with the right color, but then the holes ain't transparent.
Question now is: After filling the canvas with a color, how can you set parts of it to translucent?
If there's a more efficient/performant way to do it, please let me now as well - getting rid of the saveLayer() call would be great...
Any advise is welcome.
Thank you.
Try my version:
class Highlighter extends CustomPainter {
ValueListenable<double> valueListenable;
Color backgroundColor;
Rect target;
Highlighter({this.valueListenable, this.backgroundColor = Colors.amber, this.target = const Rect.fromLTWH(145, 320, 100, 100)})
: super(repaint: valueListenable);
#override
void paint(Canvas canvas, Size size) {
bool withRestore = false;
if (withRestore) {
//with canvas.restore
canvas.saveLayer(Rect.largest, Paint());
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), Paint()..color = backgroundColor.withOpacity(0.4));
canvas.drawRect(target, Paint()..blendMode = BlendMode.clear);
canvas.restore();
} else {
//without canvas.restore
Paint backgroundPaint = Paint();
backgroundPaint.blendMode = BlendMode.src;
backgroundPaint.color = backgroundColor.withOpacity(0.4);
// // Step 1: Draw the background:
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, target.top), backgroundPaint);
canvas.drawRect(Rect.fromLTWH(0, 0, target.left, size.height), backgroundPaint);
canvas.drawRect(Rect.fromLTWH(target.left + target.width, 0, target.left, size.height), backgroundPaint);
canvas.drawRect(Rect.fromLTWH(0, target.top + target.height, size.width, target.top), backgroundPaint);
}
}
#override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
The difficulty was to fade in/out the holes from the background (yellow) barrier. The approaches mentioned by #cloudpham93 and #YeasinSheikh do work, as long as you just want to cut a hole into the barrier.
If the holes should fade in/out however, the following steps are needed:
Call setLayer() and pass a Paint() with blendMode set to srcOver.
Draw the background barrier with the desired opacity.
Call setLayer() again, but pass a Paint() with blendMode set to dstOut.
Draw draw the holes with the desired opacity.
Call restore() twice. The first call of restore() will overwrite the opacity of the pixels on the background layer. The second call will draw the background layer onto whatever is underneath it.
Thanks for all the advise!
I want to create widget using custom painter like following with touch gesture;
Draw svg of this image. Then convert into flutter paint code using
https://fluttershapemaker.com/
Add the touchable package as dependency in your pubspec.yaml
https://github.com/nateshmbhat/touchable
Example :
CanvasTouchDetector(
builder: (context) =>
CustomPaint(
painter: MyPainter(context)
)
)
class MyPainter extends CustomPainter {
final BuildContext context ;
MyPainter(this.context); // context from CanvasTouchDetector
#override
void paint(Canvas canvas, Size size) {
var myCanvas = TouchyCanvas(context,canvas);
myCanvas.drawCircle(Offset(10, 10), 60, Paint()..color=Colors.orange ,
onTapDown: (tapdetail) {
print("orange Circle touched");
},
onPanDown:(tapdetail){
print("orange circle swiped");
}
);
myCanvas.drawLine(
Offset(0, 0),
Offset(size.width - 100, size.height - 100),
Paint()
..color = Colors.black
..strokeWidth = 50,
onPanUpdate: (detail) {
print('Black line Swiped'); //do cooler things here. Probably change app state or animate
});
}
}
At the moment I can draw rectangles using CustomPainter. Below the code inside the paint method of my CustomPainter.
for (var rectPoints in rectangles) {
paint.color = rectPoints.color;
paint.strokeWidth = rectPoints.strokeWidth;
if (rectPoints.selected != null && rectPoints.selected == true) {
paint.color = Colors.black45;
}
var rect = Rect.fromLTWH(
rectPoints.startPoint.dx,
rectPoints.startPoint.dy,
rectPoints.endPoint.dx - rectPoints.startPoint.dx,
rectPoints.endPoint.dy - rectPoints.startPoint.dy);
canvas.drawRect(rect, paint);
}
var rect = Rect.fromLTWH(startPoint.dx, startPoint.dy,
endPoint.dx - startPoint.dx, endPoint.dy - startPoint.dy);
canvas.drawRect(rect, paint);
A rectangle is a custom object with startPoint, endPoint and some other properties needed to draw that specific rectangle. Now I want to select a rectangle and re-position it. Any help would be appreciated. Thanks
You'll need to track the state of the rectangles' positions independent of the canvas drawing. The easiest way to do that is to use a StatefulWidget. You'll also need to use a GestureDetector to capture the pan events. Then you can wire up the gesture details to the position of the rectangles and call the painter to redraw everything.
Here's a simple app that shows how to do it with one rectangle. Should be straightforward to expand it to handle multiple ones.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Draggable Custom Painter',
home: Scaffold(
body: CustomPainterDraggable(),
),
);
}
}
class CustomPainterDraggable extends StatefulWidget {
#override
_CustomPainterDraggableState createState() => _CustomPainterDraggableState();
}
class _CustomPainterDraggableState extends State<CustomPainterDraggable> {
var xPos = 0.0;
var yPos = 0.0;
final width = 100.0;
final height = 100.0;
bool _dragging = false;
/// Is the point (x, y) inside the rect?
bool _insideRect(double x, double y) =>
x >= xPos && x <= xPos + width && y >= yPos && y <= yPos + height;
#override
Widget build(BuildContext context) {
return GestureDetector(
onPanStart: (details) => _dragging = _insideRect(
details.globalPosition.dx,
details.globalPosition.dy,
),
onPanEnd: (details) {
_dragging = false;
},
onPanUpdate: (details) {
if (_dragging) {
setState(() {
xPos += details.delta.dx;
yPos += details.delta.dy;
});
}
},
child: Container(
color: Colors.white,
child: CustomPaint(
painter: RectanglePainter(Rect.fromLTWH(xPos, yPos, width, height)),
child: Container(),
),
),
);
}
}
class RectanglePainter extends CustomPainter {
RectanglePainter(this.rect);
final Rect rect;
#override
void paint(Canvas canvas, Size size) {
canvas.drawRect(rect, Paint());
}
#override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
I have developed a library called
touchable for the purpose of adding gesture callbacks to each individual shape you draw on the canvas. You can draw your shapes and add onPanUpdate or onTapDown callbacks to drag your shape around.
Here's what you can do to detect touch and drag on your circle.
Here's a small example taken directly from the pub dev site :
Wrap your CustomPaint widget with CanvasTouchDetector. It takes a builder function as argument that expects your CustomPaint widget as shown below.
import 'package:touchable/touchable.dart';
CanvasTouchDetector(
builder: (context) =>
CustomPaint(
painter: MyPainter(context)
)
)
Inside your CustomPainter class's paint method , create and use the TouchyCanvas object (using the context obtained from the CanvasTouchDetector and canvas) to draw your shape and you can give gesture callbacks like onPanUpdate , onTapDown here to detect your drag events.
var myCanvas = TouchyCanvas(context,canvas);
myCanvas.drawRect( rect , Paint() , onPanUpdate: (detail){
//This callback runs when you drag this rectangle. Details of the location can be got from the detail object.
//Do stuff here. Probably change your state and animate
});
Flutter provides several ways for masks based on paths i.e. clip paths. I am trying to figure out a way where one could take an image with transparency layer like example below and use that image to mask another image / view or as a general mask.
My first instinct was to look at CustomPaint class, but I can't figure it out past this initial idea.
Flutter has BoxDecoration class that takes in BlendMode enum. By utilising these you can achieve various mask effects using images, for my particular case above dstIn was a solution.
I have posted an answer to my own same problem here, using a custom painter class with a squircle mask and image.
#override
void paint(Canvas canvas, Size size) {
if (image != null && mask != null) {
var rect = Rect.fromLTRB(0, 0, 200, 200);
Size outputSize = rect.size;
Paint paint = new Paint();
//Mask
Size maskInputSize = Size(mask.width.toDouble(), mask.height.toDouble());
final FittedSizes maskFittedSizes =
applyBoxFit(BoxFit.cover, maskInputSize, outputSize);
final Size maskSourceSize = maskFittedSizes.source;
final Rect maskSourceRect = Alignment.center
.inscribe(maskSourceSize, Offset.zero & maskInputSize);
canvas.saveLayer(rect, paint);
canvas.drawImageRect(mask, maskSourceRect, rect, paint);
//Image
Size inputSize = Size(image.width.toDouble(), image.height.toDouble());
final FittedSizes fittedSizes =
applyBoxFit(BoxFit.cover, inputSize, outputSize);
final Size sourceSize = fittedSizes.source;
final Rect sourceRect =
Alignment.center.inscribe(sourceSize, Offset.zero & inputSize);
canvas.drawImageRect(
image, sourceRect, rect, paint..blendMode = BlendMode.srcIn);
canvas.restore();
}
}
Result: