How to draw a text inside rectangle in flutter - flutter

Hi I want to draw a filled rect with a text inside using canvas.
This is my code:
Rect rect = Rect.fromLTWH(x,y,size,size,);
Paint paint = Paint()..color = Colors.blue;
canvas.drawRRect(RRect.fromRectAndRadius(rect, Radius.circular(100.0)),paint,);
I don't know how to put a text inside a rect. Please help

Use TextPainter class.
You can play around with the offset yourself
TextPainter painter;
painter = TextPainter(
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
);
painter.text = TextSpan(
text: 'Sample Text',
style: TextStyle(
color: Colors.black,
fontSize: 40.0,
),
);
Offset position = Offset(
x+2.0,
y+2.0,
);
painter.layout();
painter.paint(canvas, position);

Related

How to draw vertical text using canvas.drawParagraph in Flutter

I want to draw vertical text directly using canvas, but I didn't find such methods,
I only found related parameter TextDirection, but it only support left--right or right--left.
Here is my code:
void drawMeasurementTag(Canvas canvas, Rect limitRect) {
String text = "this is content";
double textFont = 18;
double textWidth = getTextPainter(text, textFont).width;
Paragraph paragraph = getTextBuilder(
text, textFont, Colors.red);
paragraph.layout(ParagraphConstraints(width: textWidth));
tagPos =Offset(0,0) ;
canvas.drawParagraph(paragraph, tagPos);
}
ui.Paragraph getTextBuilder(String text, double textFont, Color color) {
Paint paint = Paint();
paint.color = getTagBackgroundColor();
var builder = ui.ParagraphBuilder(ui.ParagraphStyle(
textAlign: TextAlign.center,
fontSize: textFont,
textDirection: TextDirection.ltr,
maxLines: 1,
));
builder.pushStyle(
ui.TextStyle(
color: color,
textBaseline: TextBaseline.alphabetic,
background: paint),
);
builder.addText(text);
ui.Paragraph paragraph = builder.build();
return paragraph;
}
this is what I want to achieve:
`
You can rotate your widgets in flutter by math package:
import 'dart:math' as math;
Then use this to rotate by 90 degrees:
Transform.rotate(
angle: -math.pi / 2, // edit this angle
child: Card(
child: Text("Rotated text"),
),
)

Flutter: how to paint a Font Awesome Icon?

I am using CustomPainter to draw in flutter as per this question: Flutter: How to paint an Icon on Canvas?
final icon = Icons.cake;
TextPainter textPainter = TextPainter(textDirection: TextDirection.rtl);
textPainter.text = TextSpan(
text: String.fromCharCode(icon.codePoint),
style: TextStyle(fontSize: 20.0, fontFamily: icon.fontFamily));
textPainter.layout();
textPainter.paint(canvas, Offset(200.0, 200.0));
This works for Material Design Icons. However I would like to use the same techniqe to paint Font Awesome Icons. I am using the font_awesome_flutter 8.5.0 package, and this is my code:
final icon = Icon(FontAwesomeIcons.fish, size: 20, color: Colors.teal[700]);
TextPainter textPainter = TextPainter(textDirection: TextDirection.rtl);
textPainter.text = TextSpan(
text: String.fromCharCode(icon.codePoint),
style: TextStyle(fontSize: 20.0, fontFamily: icon.fontFamily));
textPainter.layout();
textPainter.paint(canvas, Offset(200.0, 200.0));
I am getting a message from the IDE saying that "The getter 'codePoint' isn't defined for the class 'Icon'". How can I fix this please?
Thanks to #pskink for helping me figure out this answer:
final fishCodePoint = FontAwesomeIcons.fish.codePoint;
print('The codePoint is $fishCodePoint');
final fishFontPackage = FontAwesomeIcons.fish.fontPackage;
print('The fontPackage is $fishFontPackage');
final fishFontFamily = FontAwesomeIcons.fish.fontFamily;
print('The fontFamily is $fishFontFamily');
TextPainter textPainter = TextPainter(textDirection: TextDirection.rtl);
textPainter.text = TextSpan(
text: String.fromCharCode(fishCodePoint),
style: TextStyle(
fontSize: 40.0,
fontFamily: fishFontFamily,
package: fishFontPackage));
textPainter.paint(canvas, Offset(50.0, 50.0));

How to create text inside marker with google_maps_flutter?

How to implement a marker on Google Maps flutter with text on the marker. Image for reference:
https://i.stack.imgur.com/W6oqG.jpg
I managed to solve with this method
Future<BitmapDescriptor> createCustomMarkerBitmap(String title) async {
TextSpan span = new TextSpan(
style: new TextStyle(
color: Prefs.singleton().getTheme() == 'Dark'
? Colors.white
: Colors.black,
fontSize: 35.0,
fontWeight: FontWeight.bold,
),
text: title,
);
TextPainter tp = new TextPainter(
text: span,
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
);
tp.text = TextSpan(
text: title.toStringAsFixed(0),
style: TextStyle(
fontSize: 35.0,
color: Theme.of(context).accentColor,
letterSpacing: 1.0,
fontFamily: 'Roboto Bold',
),
);
PictureRecorder recorder = new PictureRecorder();
Canvas c = new Canvas(recorder);
tp.layout();
tp.paint(c, new Offset(20.0, 10.0));
/* Do your painting of the custom icon here, including drawing text, shapes, etc. */
Picture p = recorder.endRecording();
ByteData pngBytes =
await (await p.toImage(tp.width.toInt() + 40, tp.height.toInt() + 20))
.toByteData(format: ImageByteFormat.png);
Uint8List data = Uint8List.view(pngBytes.buffer);
return BitmapDescriptor.fromBytes(data);
}
how to use:
BitmapDescriptor bitmapDescriptor = await createCustomMarkerBitmap(...);
Marker marker = Marker(
/* in addition to your other properties: */
icon: bitmapDescriptor
);
You can either do it manually using Canvas and Painter. Or you could use this package which does the exact same thing asked in the question.
https://pub.dev/packages/label_marker
Just go through the overview once and you can see if it is for you or not. I really hope it helps. And yeah. I made it :)

Align custom painted text in flutter

I need make custom widget (in Flutter) which contains text on specific position. When I draw text by TextPainter, I set TextAlign to center. Text is still drawn with left align. What am I doing wrong?
TextSpan span = TextSpan(style: TextStyle(color: Colors.white, fontSize: textSize), text: 'T');
TextPainter tp = TextPainter(text: span, textAlign: TextAlign.center, textDirection: TextDirection.ltr);
tp.layout();
tp.paint(canvas, Offset(pos.x, pos.y));
To simply center the text on the canvas, calculate its offset:
void _paintText(Canvas canvas, Size size) {
final textSpan = TextSpan(
text: 'n/a',
);
final textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
);
textPainter.layout();
textPainter.paint(
canvas,
Offset(
// Do calculations here:
(size.width - textPainter.width) * 0.5,
(size.height - textPainter.height) * 0.5,
),
);
}
for the X position make sure layout is set to 0 for min an max width
textPainter.layout(minWidth: 0, maxWidth: 0);
for the Y position you have to substract the height of the text itself
final position = Offset(xPOS, yPOS - (textPainter.height / 2));
here is an example code
void _drawTextAt(String text, Offset position, Canvas canvas) {
final textStyle = TextStyle(
color: Colors.black,
fontSize: 30,
);
final textSpan = TextSpan(
text: 'O',
style: textStyle,
);
final textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
textAlign: TextAlign.center);
textPainter.layout(minWidth: 0, maxWidth: 0);
Offset drawPosition =
Offset(position.dx, position.dy - (textPainter.height / 2));
textPainter.paint(canvas, drawPosition);
}
To use this function call e.g.
_drawTextAt('A', Offset(20, 20), canvas);
double width = 100, height = 200, r = 63;
canvas.drawCircle(Offset(width, height), r, Paint()..color = Colors.purple);
ParagraphBuilder paragraphBuilder =
ParagraphBuilder(ParagraphStyle(textAlign: TextAlign.center))
..addText('Hello');
ParagraphConstraints paragraphConstraints =
ParagraphConstraints(width: r * 2);
Paragraph paragraph = paragraphBuilder.build()
..layout(paragraphConstraints);
canvas.drawParagraph(
paragraph, Offset(width - r, height - paragraph.height / 2));
By using Alignment.inscribe, you can align the text in any way. :)
extension CanvasExt on Canvas {
void drawTextInRect(
Rect rect,
Alignment alignment,
TextPainter painter,
) {
final offsetRect = alignment.inscribe(painter.size, rect);
painter.paint(this, offsetRect.topLeft);
}
}
I used drawParagraph and it works well
final ui.ParagraphBuilder paragraphBuilder = ui.ParagraphBuilder(
ui.ParagraphStyle(textDirection: ui.TextDirection.ltr),
)
..addText('Your Text');
final ui.Paragraph paragraph = paragraphBuilder.build()
..layout(ui.ParagraphConstraints(width: textSize.width));
canvas.drawParagraph(paragraph, textOffset);
you can change the ParagraphStyle the way you like.

Drawing text in a specific spot using flutter

For text drawing on canvas, a fairly simple construction can be used:
void drawName(Canvas context, String name, double x, double y)
{
TextSpan span = new TextSpan(
style: new TextStyle(color: Colors.blue[800], fontSize: 24.0,
fontFamily: 'Roboto'), text: name);
TextPainter tp = new TextPainter(
text: span, textAlign: TextAlign.left, textDirection: `
` TextDirection.ltr);
tp.layout();
tp.paint(context, new Offset(x, y));
}
Is it possible to draw text at an angle, for example 45 degrees, or 90 degrees (vertically from the bottom up)?
To rotate text on a canvas, you can use canvas transforms rather than rotating the entire canvas.
That looks something like this:
#override
void paint(Canvas canvas, Size size) {
// save is optional, only needed you want to draw other things non-rotated & translated
canvas.save();
canvas.translate(100.0, 100.0);
canvas.rotate(3.14159/4.0);
TextSpan span = new TextSpan(
style: new TextStyle(color: Colors.blue[800], fontSize: 24.0,
fontFamily: 'Roboto'), text: "text");
TextPainter tp = new TextPainter(
text: span, textDirection: TextDirection.ltr);
tp.layout();
tp.paint(canvas, new Offset(0.0, 0.0));
// optional, if you saved earlier
canvas.restore();
}
Note that I'm translating then rotating, because if you translate after or even use the offset you'll probably get a different result than what you want. Also, once you start using transforms (translate & rotate) you probably want to save the transform state and then restore after you draw whatever you want transformed, at least if you're drawing anything other than the rotated text.
It sounds like you are looking for a Transformation. There is a general Transform Widget, but there is also a more specific RotatedBox Widget that sounds like it will be a perfect fit for you.
new RotatedBox(
quarterTurns: 3,
child: const Text('Hello World!'),
)
If you need more control over the rotation (to use something other than 90 degree increments) you should be able to achieve this the Transform Widget and a Matrix4.rotationZ
new Container(
color: Colors.blue,
child: new Transform(
transform: new Matrix4.rotationZ(-0.785398),
child: new Container(
padding: const EdgeInsets.all(8.0),
color: const Color(0xFFE8581C),
child: const Text('Apartment for rent!'),
),
),
)
A function that draws text at a specified angle:
void drawText(Canvas context, String name, double x, double y, double angleRotationInRadians)
{
context.save();
context.translate(x, y);
context.rotate(angleRotationInRadians);
TextSpan span = new TextSpan(
style: new TextStyle(color: Colors.blue[800], fontSize: 24.0,
fontFamily: 'Roboto'), text: name);
TextPainter tp = new TextPainter(
text: span, textAlign: TextAlign.left,
textDirection: TextDirection.ltr);
tp.layout();
tp.paint(context, new Offset(0.0,0.0));
context.restore();
}
PS."rmtmckenzie", thank a lot for your help.