Flutter: how to paint a Font Awesome Icon? - flutter

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));

Related

Make CupertinoIcon render and not show placeholder

Based on this SO question, I tried to draw a CupertinoIcon on a Canvas:
final icon = CupertinoIcons.add;
TextPainter textPainter = TextPainter(
textDirection: TextDirection.ltr
);
textPainter.text = TextSpan(
text: String.fromCharCode(
icon.codePoint
),
style: TextStyle(
fontSize: 40.0,
fontFamily: icon.fontFamily
)
);
textPainter.layout();
textPainter.paint( canvas, Offset( params.x, params.y ) );
Note that the code is fully generic, since it uses properties like codePoint of the CupertinoIcon.
While this code renders the other painter commands, the code unfortunately renders a placeholder of the icon in Google Chrome:
How do I make the icon appear?
The icon appears, as soon as the package parameter gets added to TextStyle:
TextStyle(
fontSize: 60.0,
fontFamily: icon.fontFamily,
color: Colors.red,
package: icon.fontPackage // Need to make the icon appear
)
The documentation says this:
To use a font family defined in a package, the package argument must be provided.

How to draw a text inside rectangle in 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);

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 :)

Make Emojis bigger in text?

Any idea how to make only the fontsize of emojis larger in the Text() widget?
The issue is that the Text() widget parses the emojis automatically. Sure, I can increase the overall text size, but I want the text to stay at the same fontsize.
If you want to auto increase size of emojis in chat message you can use this method:
static final RegExp REGEX_EMOJI = RegExp(
r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])');
Widget _buildContent(String content) {
final Iterable<Match> matches = REGEX_EMOJI.allMatches(content);
if (matches.isEmpty)
return Text(
'${content}',
style: TextStyle(
fontSize: 14.0,
fontWeight: FontWeight.w500,
color: Colors.black,
),
);
return RichText(
text: TextSpan(children: [
for (var t in content.characters)
TextSpan(
text: t,
style: TextStyle(
fontSize: REGEX_EMOJI.allMatches(t).isNotEmpty ? 20.0 : 12.0,
color: Colors.black,
)),
]));
}
You can use the widget RichText
RichText(
text: TextSpan(
text: 'hello',
children: <TextSpan>[
TextSpan(text: '🙂', style: TextStyle(fontSize: 30))
]
),
),
I was facing the same issue and find beginning of solution here
I've modified the code a little to allow showing text and emoji with different font size.
import 'package:flutter/material.dart';
/// Widget to render emoji and text with different font size
class EmojisText extends StatelessWidget {
const EmojisText({
Key? key,
required this.text,
required this.color,
required this.emojiSize,
required this.textSize,
}) : super(key: key);
///The text which emoji and alpha-numeric characters
///emoji can be absent
final String text;
/// THe font size to set to emoji
final double emojiSize;
/// The font size to set to text
final double textSize;
/// the color of the text
final Color color;
#override
Widget build(BuildContext context) {
return RichText(
text: _buildText(),
);
}
TextSpan _buildText() {
final children = <TextSpan>[];
final runes = text.runes;
for (int i = 0; i < runes.length; /* empty */) {
int current = runes.elementAt(i);
// we assume that everything that is not
// in Extended-ASCII set is an emoji...
final isEmoji = current > 255;
final shouldBreak = isEmoji ? (x) => x <= 255 : (x) => x > 255;
final chunk = <int>[];
while (!shouldBreak(current)) {
chunk.add(current);
if (++i >= runes.length) break;
current = runes.elementAt(i);
}
children.add(
TextSpan(
text: String.fromCharCodes(chunk),
style: TextStyle(
fontSize: isEmoji ? emojiSize : textSize,
color: color,
),
),
);
}
return TextSpan(children: children);
}
}

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.