Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing text in a specific spot using flutter

Tags:

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

like image 723
Michael Kanzieper Avatar asked Aug 04 '26 18:08

Michael Kanzieper


1 Answers

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.

like image 158
rmtmckenzie Avatar answered Aug 06 '26 09:08

rmtmckenzie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!