分享

flutter TextPainter 的用法

 程序员读书空间 2023-12-08 发布于浙江

本文章基于 Flutter 3.16.2   Dart SDK 3.2.2。

TextPainter 是 Flutter 中用于在 Canvas 上绘制文本的类。它允许您在自定义的 CustomPainter 中使用 drawText 方法来绘制文本,并可以控制文本的位置、颜色、字体等属性。

import 'package:flutter/material.dart';
class CustomTextPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { TextPainter textPainter = TextPainter( text: TextSpan( text: 'Hello, Flutter!', style: TextStyle(color: Colors.black, fontSize: 24), ), textAlign: TextAlign.center, textDirection: TextDirection.ltr,    )..layout(); textPainter.paint(canvas, Offset(0, 0)); }
@override bool shouldRepaint(CustomPainter oldDelegate) { return oldDelegate != this; }}
class CustomTextWidget extends StatelessWidget { @override Widget build(BuildContext context) { return CustomPaint( size: Size(200, 100), painter: CustomTextPainter(), ); }}
void main() { runApp(MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Custom Text Painter Example'), ), body: Center( child: CustomTextWidget(), ), ), ));}

运行效果如下:就是绘制出一条普通的文本

本文案例使用 DartPad 在线测试

https://dartpad.cn/?id

现在,绘制一条文本,并在文本下绘制一条下划线(当然你可以是其他任意的图形),核心代码如下

class UnderlinePainter extends CustomPainter {  @override  void paint(Canvas canvas, Size size) {    Paint paint = Paint()      ..color = Colors.black      ..strokeCap = StrokeCap.round      ..strokeWidth = 4; // 设置下划线宽度
// 绘制文本 TextSpan textSpan = TextSpan( text: 'Hello, Flutter!', // 文本内容 style: TextStyle(color: Colors.black), ); TextPainter textPainter = TextPainter( text: textSpan, textAlign: TextAlign.center, textDirection: TextDirection.ltr) ..layout(); textPainter.paint(canvas, Offset(0, 0));
// 绘制下划线 canvas.drawLine(new Offset(0, textPainter.height), new Offset(size.width, textPainter.height), paint); }
@override bool shouldRepaint(CustomPainter oldDelegate) { return oldDelegate != this; }}

TextSpan是一个用于表示文本的类,TextSpan包含以下属性:

  • text: 要绘制的文本内容。

  • style: 文本的样式,包括字体、颜色、大小等。

  • alignment: 文本的对齐方式。

  • textDirection: 文本的方向,例如从左到右或从右到左。

TextPainter类用于在Canvas上绘制文本,常用属性包括:

  1. text:要绘制的文本内容。

  2. style:文本的样式,包括字体、颜色、大小等。

  3. alignment:文本的对齐方式。

  4. textDirection:文本的方向,例如从左到右或从右到左。

  5. color:文本的颜色。

  6. fontSize:文本的字体大小。

  7. fontFamily:文本的字体类型。

  8. textAlign:文本的对齐方式,例如居中、左对齐、右对齐等。

  9. maxLines:文本的最大行数,超过这个行数将会出现溢出情况。

  10. overflow:文本的溢出方式,例如裁剪、滚动等。

  11. textScaleFactor:文本的缩放因子,可以用于实现缩放效果。

  12. decorationColor:文本装饰的颜色,例如线条的颜色。

  13. decoration:文本装饰的类型,例如删除线、上划线、下划线等。

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多