在颤动中对齐自定义绘制的文本

Cly*_*yde 7 flutter

我需要制作包含特定位置文本的自定义小部件(在 Flutter 中)。当我通过 TextPainter 绘制文本时,我将 TextAlign 设置为居中。文本仍然以左对齐方式绘制。我究竟做错了什么?

谢谢(我很抱歉我的英语不好)

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));
Run Code Online (Sandbox Code Playgroud)

And*_*eev 14

在 Flutter 中将自定义绘制的文本与 CustomPainter 对齐

要简单地将文本在画布上居中,请计算其偏移量:

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,
    ),
  );
}
Run Code Online (Sandbox Code Playgroud)


Mor*_*ool 7

对于 X 位置,确保布局设置为 0 最小和最大宽度

textPainter.layout(minWidth: 0, maxWidth: 0); 
Run Code Online (Sandbox Code Playgroud)

对于 Y 位置,您必须减去文本本身的高度

final position = Offset(xPOS, yPOS - (textPainter.height / 2));
Run Code Online (Sandbox Code Playgroud)

这是一个示例代码

void _drawTextAt(String text, Offset position, Canvas canvas) {
    final textStyle = TextStyle(
      color: Colors.black,
      fontSize: 30,
    );
    final textSpan = TextSpan(
      text: 'O',
      style: textStyle,
    );
    final textPainter = TextPainter(
        text: textSpan,
        textDirection: TextDirection.ltr,
        textAlign: TextAlign.center);
    textPainter.layout(minWidth: 0, maxWidth: 0);
    Offset drawPosition =
        Offset(position.dx, position.dy - (textPainter.height / 2));
    textPainter.paint(canvas, drawPosition);
  }
Run Code Online (Sandbox Code Playgroud)

要使用此函数调用,例如

  _drawTextAt('A', Offset(20, 20), canvas);
Run Code Online (Sandbox Code Playgroud)