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

时间:2019-03-25 13:37:02

标签: 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));

4 个答案:

答案 0 :(得分:7)

Align a custom painted text with CustomPainter in Flutter

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

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,
    ),
  );
}

答案 1 :(得分:0)

对于X位置,请确保将布局设置为0以获得最小最大宽度

textPainter.layout(minWidth: 0, maxWidth: 0); 

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

final position = Offset(xPOS, yPOS - (textPainter.height / 2));

这是示例代码

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);
  }

要使用此功能,请调用

  _drawTextAt('A', Offset(20, 20), canvas);

答案 2 :(得分:0)

我使用了drawParagraph,效果很好

final ui.ParagraphBuilder paragraphBuilder = ui.ParagraphBuilder(
        ui.ParagraphStyle(textDirection: ui.TextDirection.ltr),
      )
      ..addText('Your Text');
final ui.Paragraph paragraph = paragraphBuilder.build()
        ..layout(ui.ParagraphConstraints(width: textSize.width));
canvas.drawParagraph(paragraph, textOffset);

您可以按照自己的方式更改ParagraphStyle。

答案 3 :(得分:0)

通过使用 Alignment.inscribe,您可以以任何方式对齐文本。 :)

extension CanvasExt on Canvas {
    void drawTextInRect(
        Rect rect,
        Alignment alignment,
        TextPainter painter,
    ) {
        final offsetRect = alignment.inscribe(painter.size, rect);
        painter.paint(this, offsetRect.topLeft);
    }
}