Understanding Canvas in Flutter
A Canvas in Flutter is like a blank drawing board. It's an interface that lets you draw shapes, lines, images, and yes, even text, directly onto the screen.
Using a canvas gives you fine-grained control over exactly where and how things appear, which is great for custom widgets, charts, or drawing apps.
While you usually use standard widgets like Text
to show words, sometimes you need to draw text as part of a custom drawing process on a canvas. This is where TextPainter
comes in handy.
How to Draw Text on a Canvas
To draw text on a canvas, you'll typically use a combination of CustomPaint
(which provides the canvas) and TextPainter
(which helps you prepare and draw the text).
Here’s the basic process:
1. Define the Text Style
First, decide how your text should look. You create a TextStyle
object, just like you would for a regular Text
widget. You can set color, font size, weight, etc.
final textStyle = TextStyle(
color: Colors.black,
fontSize: 40,
);
2. Create a TextSpan and TextPainter
A TextSpan
holds the text content and its style. Then, a TextPainter
is created with this TextSpan
. The TextPainter
is the tool that measures and paints the text.
You also need to tell the TextPainter
the text direction (like left-to-right).
final textSpan = TextSpan(
text: 'Hello, Canvas!',
style: textStyle,
);
final textPainter = TextPainter(
text: textSpan,
textDirection: ui.TextDirection.ltr,
);
3. Prepare for Layout
Before you can draw, you need to calculate the text's size based on the style and content. This is done with the layout()
method.
textPainter.layout();
4. Define Position and Draw
Decide where on the canvas you want the top-left corner of your text to appear. You use an Offset
for this.
Finally, call the paint()
method on the TextPainter
, passing the canvas and the offset position.
final offset = Offset(50, 100); // Position (x, y)
textPainter.paint(canvas, offset);
This process happens inside the paint
method of a CustomPainter
class, which is then used within a CustomPaint
widget.
Using TextPainter
on a canvas gives you great flexibility for drawing text as part of complex graphical elements in your Flutter app.