Flutter: How to paint an Icon on Canvas?
4,419
Solution 1
Create a Paragraph
containing the code point in the correct font, style it as needed, then draw it.
final icon = Icons.add;
var builder = ui.ParagraphBuilder(ui.ParagraphStyle(
fontFamily: icon.fontFamily,
))
..addText(String.fromCharCode(icon.codePoint));
var para = builder.build();
para.layout(const ui.ParagraphConstraints(width: 60));
canvas.drawParagraph(para, const Offset(20, 20));
Solution 2
@Richard Heap and @pskink based on your answers I was trying and came up with this: Thank you guys this is what I too was searching for.
final icon = Icons.add;
TextPainter textPainter = TextPainter(textDirection: TextDirection.rtl);
textPainter.text = TextSpan(text: String.fromCharCode(icon.codePoint),
style: TextStyle(fontSize: 40.0,fontFamily: icon.fontFamily));
textPainter.layout();
textPainter.paint(canvas, Offset(50.0,50.0));
Solution 3
Just to add a small but important detail, if you are trying to render an icon from an external icon pack (such a Material Design Icons or FontAwesome) you need to add the package
parameter in the TextStyle
.
final icon = MdiIcons.check;
TextPainter textPainter = TextPainter(textDirection: TextDirection.ltr);
textPainter.text = TextSpan(
text: String.fromCharCode(icon.codePoint),
style: TextStyle(
color: Colors.black,
fontSize: size,
fontFamily: icon.fontFamily,
package: icon.fontPackage, // This line is mandatory for external icon packs
),
);
textPainter.layout();
textPainter.paint(canvas, Offset(x, y));
Author by
IronHawk
Updated on November 21, 2022Comments
-
IronHawk over 1 year
I'm using a
CustomPainter
to draw in Flutter like this:@override void paint(Canvas canvas, Size size) { canvas.drawRect(...); canvas.drawImage(...); ... }
How to draw an
Icon
oncanvas
? -
Simran Aswani about 4 yearsis there a way to add a GestureDetector on the icon ?
-
Ant D about 4 years1) If you mean IconButton widget - It has an onPressed function. 2) If you want to add the above CustomPainter add it as a child to Container. This Container's parent can be a GeatureDetector or InkWell.
-
user2233706 over 3 yearsYou need to also pass the color to TextStyle. Otherwise, you won't see anything.
-
opsb about 3 yearsThis didn't work for pub.dev/packages/font_awesome_flutter, but @Ludonope's answer did