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));
                
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,
    ),
  );
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With