对于在画布上绘制文本,可以使用相当简单的构造:

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

是否可以以45度或90度(从下往上垂直)的角度绘制文本?

最佳答案

要旋转画布上的文本,可以使用画布变换而不是旋转整个画布。

看起来像这样:

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

请注意,我先平移然后旋转,因为如果您在平移之后甚至使用平移,则可能会得到与所需结果不同的结果。另外,一旦开始使用转换(转换和旋转),您可能想要保存转换状态,然后在绘制要转换的内容后恢复,至少在绘制除旋转文本之外的其他内容时。

09-04 18:26
查看更多