在下面的示例中,使用以下文本:
Hello, world.
Another line of text.
A line of text that wraps around.
红色矩形用来显示宽度指标,高度可以忽略。
宽度
这是段落的宽度,由ParagraphConstraints
的宽度参数定义,当段落布局时确定。它不依赖于段落文本内容。
![enter image description here](https://istack.dev59.com/Tm7Fr.webp)
最长行
这是考虑软换行后的最长文本行的长度。它小于或等于段落的宽度。
![enter image description here](https://istack.dev59.com/oZpdG.webp)
最大内在宽度
如果有选择,这是段落想要的宽度。如果没有软换行,它就是最长行的宽度。也就是说,如果“A line of text that wraps around.”没有被强制换行,它的宽度就是最大内在宽度。
![enter image description here](https://istack.dev59.com/CvE3v.webp)
最小内在宽度
这是段落可以不用强制断词就能达到的最窄宽度。您可以在下面的示例中看到,minIntrinsicWidth是单词“Another”的宽度。
![enter image description here](https://istack.dev59.com/VOdgQ.webp)
补充代码
如果您想自己试玩,请创建一个新的Flutter项目,并用以下代码替换 main.dart 。
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui' as ui;
void main() {
debugPaintSizeEnabled = false;
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.white,
body: HomeWidget(),
),
);
}
}
class HomeWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: CustomPaint(
size: Size(300, 200),
painter: MyPainter(),
),
);
}
}
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final text = 'Hello, world.\nAnother line of text.\nA line of text that wraps around.';
final textStyle = ui.TextStyle(
color: Colors.black,
fontSize: 30,
);
final paragraphStyle = ui.ParagraphStyle(
textDirection: TextDirection.ltr,
);
final paragraphBuilder = ui.ParagraphBuilder(paragraphStyle)
..pushStyle(textStyle)
..addText(text);
final constraints = ui.ParagraphConstraints(width: 300);
final paragraph = paragraphBuilder.build();
paragraph.layout(constraints);
final offset = Offset(0, 0);
canvas.drawParagraph(paragraph, offset);
final left = 0.0;
final top = 0.0;
final right = paragraph.minIntrinsicWidth;
final bottom = paragraph.height;
final rect = Rect.fromLTRB(left, top, right, bottom);
final paint = Paint()
..color = Colors.red
..style = PaintingStyle.stroke
..strokeWidth = 1;
canvas.drawRect(rect, paint);
}
@override
bool shouldRepaint(CustomPainter old) {
return false;
}
}
另请参阅