如何使用TextPainter绘制文本?

时间:2016-12-29 00:05:53

标签: dart flutter

我可能从根本上误解了它是如何工作的所以请纠正我错在哪里documentation for CustomPainter's paint method说,“要在Canvas上绘制文本,使用TextPainter”所以在我的MyCustomPainter的绘画方法中我有以下内容:

TextSpan span = new TextSpan(text: 'Yrfc');
TextPainter tp = new TextPainter(text: span, textAlign: TextAlign.left);
tp.layout();
tp.paint(canvas, new Offset(5.0, 5.0));

我尝试了各种偏移(Offset.zero, Offset.infinite, new Offset(10.0, 10.0),但我无法看到屏幕上绘制的文字。

3 个答案:

答案 0 :(得分:9)

我在输入这个问题的时候找到了答案,但我现在已经和它进行了一段时间的摔跤,所以如果它能帮到其他任何人就发布。

解决这个问题的原因是将TextSpan行更改为:

TextSpan span = new TextSpan(style: new TextStyle(color: Colors.grey[600]), text: 'Yrfc');

显然它是无形地绘制文本或者是白色(背景)颜色,因为我没有明确地选择颜色。

答案 1 :(得分:5)

在TextPainter构造函数中,还需要指定 TextDirection 参数,否则您将收到异常:

TextSpan span = new TextSpan(style: new TextStyle(color: Colors.blue[800]), text: name);
TextPainter tp = new TextPainter(text: span, textAlign: TextAlign.left, textDirection: TextDirection.ltr);
tp.layout();
tp.paint(context, new Offset(5.0, 5.0));

答案 2 :(得分:0)

如何使用TextPainter绘制文本

enter image description here

要在Flutter中绘画,请使用CustomPaint小部件。 CustomPaint小部件将CustomPainter对象作为参数。在该类中,您必须重写paint方法,该方法为您提供了可以在其上绘画的画布。这是在上图中绘制文本的代码。

@override
void paint(Canvas canvas, Size size) {
  final textStyle = TextStyle(
    color: Colors.black,
    fontSize: 30,
  );
  final textSpan = TextSpan(
    text: 'Hello, world.',
    style: textStyle,
  );
  final textPainter = TextPainter(
    text: textSpan,
    textDirection: TextDirection.ltr,
  );
  textPainter.layout(
    minWidth: 0,
    maxWidth: size.width,
  );
  final offset = Offset(50, 100);
  textPainter.paint(canvas, offset);
}

注意:

  • 如果您使用的是白色背景,请确保将文本颜色设置为除白色以外的其他颜色,这是默认设置。
  • Flutter努力不采用文本方向,因此您需要显式设置它。缩写ltr代表从左到右,英语等语言都使用。另一个选项是rtl(从右到左),使用阿拉伯语和希伯来语之类的语言。当在开发人员没有考虑的语言环境中使用代码时,这有助于减少错误。

上下文

这是 main.dart 代码,以便您可以在上下文中看到它。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: HomeWidget(),
      ),
    );
  }
}

class HomeWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: CustomPaint( //                       <-- CustomPaint widget
        size: Size(300, 300),
        painter: MyPainter(),
      ),
    );
  }
}

class MyPainter extends CustomPainter { //         <-- CustomPainter class
  @override
  void paint(Canvas canvas, Size size) {
    //                                             <-- Insert your painting code here.
  }

  @override
  bool shouldRepaint(CustomPainter old) {
    return false;
  }
}

另请参见

请参阅this article,以获得更完整的答案。