dart 如何使用TextPainter绘制文本?

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

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

  1. TextSpan span = new TextSpan(text: 'Yrfc');
  2. TextPainter tp = new TextPainter(text: span, textAlign: TextAlign.left);
  3. tp.layout();
  4. 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方法,该方法为您提供了一个可以在其上绘画的画布。下面是在上图中绘制文本的代码。

  1. @override
  2. void paint(Canvas canvas, Size size) {
  3. const textStyle = TextStyle(
  4. color: Colors.black,
  5. fontSize: 30,
  6. );
  7. const textSpan = TextSpan(
  8. text: 'Hello, world.',
  9. style: textStyle,
  10. );
  11. final textPainter = TextPainter(
  12. text: textSpan,
  13. textDirection: TextDirection.ltr,
  14. );
  15. textPainter.layout(
  16. minWidth: 0,
  17. maxWidth: size.width,
  18. );
  19. final xCenter = (size.width - textPainter.width) / 2;
  20. final yCenter = (size.height - textPainter.height) / 2;
  21. final offset = Offset(xCenter, yCenter);
  22. textPainter.paint(canvas, offset);
  23. }

字符串

注意事项:

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

上下文

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

  1. import 'package:flutter/material.dart';
  2. void main() => runApp(MyApp());
  3. class MyApp extends StatelessWidget {
  4. @override
  5. Widget build(BuildContext context) {
  6. return MaterialApp(
  7. home: Scaffold(
  8. body: HomeWidget(),
  9. ),
  10. );
  11. }
  12. }
  13. class HomeWidget extends StatelessWidget {
  14. @override
  15. Widget build(BuildContext context) {
  16. return Center(
  17. child: CustomPaint( // <-- CustomPaint widget
  18. size: Size(300, 300),
  19. painter: MyPainter(),
  20. ),
  21. );
  22. }
  23. }
  24. class MyPainter extends CustomPainter { // <-- CustomPainter class
  25. @override
  26. void paint(Canvas canvas, Size size) {
  27. // <-- Insert your painting code here.
  28. }
  29. @override
  30. bool shouldRepaint(CustomPainter old) {
  31. return false;
  32. }
  33. }

参见

参见this article以获得更完整的答案。

展开查看全部
relj7zay

relj7zay2#

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

0aydgbwb

0aydgbwb3#

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

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

字符串

相关问题