段落的documentation有四种获取宽度距离的方法:
请注意,tightWidth
不再出现在Flutter 1.7稳定版本中。
但是,我仍然不清楚它们之间的区别。 width
是否包含一些额外的填充?
最佳答案
在以下示例中,使用以下文本:
Hello, world.
Another line of text.
A line of text that wraps around.
红色矩形用于说明宽度度量。高度可以忽略。
宽度
这是布置段落时由
ParagraphConstraints
width参数定义的段落的宽度。它不取决于段落文本的内容。longestLine
这是考虑到软包装的最长文本行的长度。它将小于或等于段落宽度。
maxIntrinsicWidth
如果可以选择的话,这就是该段的宽度。没有软线换行时,它是最长线的宽度。即,它是“环绕的一行文本”的宽度。如果不是被迫改行的话。
minIntrinsicWidth
这是最短的段落,不会引起某些单词的自然破译。您可以在下面的示例中看到minIntrinsicWidth是单词“另一个”的宽度。
补充代码
您可以创建一个新的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.';
// draw the text
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);
// draw a rectangle around the text
final left = 0.0;
final top = 0.0;
//final right = paragraph.width;
//final right = paragraph.longestLine;
//final right = paragraph.maxIntrinsicWidth;
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;
}
}
也可以看看