Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align custom painted text in flutter

Tags:

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));
like image 405
Clyde Avatar asked Mar 25 '19 13:03

Clyde


1 Answers

Align a custom painted text with CustomPainter in Flutter

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,
    ),
  );
}
like image 123
Andrey Gordeev Avatar answered Oct 07 '22 01:10

Andrey Gordeev