dart 如何使用TextPainter绘制文本?

xzlaal3s  于 2024-01-03  发布在  其他
关注(0)|答案(3)|浏览(100)

documentation for CustomPainter's paint method说,“要在Canvas上绘制文本,请使用TextPainter“。因此,在我的MyCustomPainter的paint方法中,我有以下内容:

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),但我从来没有能够看到屏幕上绘制的文本。

ldfqzlk8

ldfqzlk81#


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

@override
void paint(Canvas canvas, Size size) {
  const textStyle = TextStyle(
    color: Colors.black,
    fontSize: 30,
  );
  const textSpan = TextSpan(
    text: 'Hello, world.',
    style: textStyle,
  );
  final textPainter = TextPainter(
    text: textSpan,
    textDirection: TextDirection.ltr,
  );
  textPainter.layout(
    minWidth: 0,
    maxWidth: size.width,
  );
  final xCenter = (size.width - textPainter.width) / 2;
  final yCenter = (size.height - textPainter.height) / 2;
  final offset = Offset(xCenter, yCenter);
  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以获得更完整的答案。

relj7zay

relj7zay2#

我在打字的时候找到了答案,但是我已经纠结了一段时间了,所以在这里发帖,以防对其他人有帮助。
解决这个问题的方法是将TextSpan行改为:
TextSpan span = new TextSpan(style: new TextStyle(color: Colors.grey[600]), text: 'Yrfc');
显然,它要么是无形地绘制文本,要么是作为白色(背景)颜色,因为我没有明确选择颜色。

0aydgbwb

0aydgbwb3#

在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(canvas, new Offset(5.0, 5.0));

字符串

相关问题