Flutter中的段落类宽度指标是什么意思?

5

段落的文档提供了四种获取宽度距离的不同方法:

width → double
段落所占用的水平空间量。

longestLine → double
段落中最左边字形的左边缘到最右边字形的右边缘之间的距离。

maxIntrinsicWidth → double
返回超过该宽度后将不会减小高度的最小宽度。

minIntrinsicWidth → double
在不使内容在其内部绘制失败的情况下,此段落可以具有的最小宽度。

请注意,tightWidth 在Flutter 1.7稳定版中已经不再出现。

尽管如此,我仍然不清楚这些指的是什么,width是否包含额外的填充?

1个回答

18
在下面的示例中,使用以下文本:
Hello, world.
Another line of text.
A line of text that wraps around.

红色矩形用来显示宽度指标,高度可以忽略。

宽度

这是段落的宽度,由ParagraphConstraints的宽度参数定义,当段落布局时确定。它不依赖于段落文本内容。

enter image description here

最长行

这是考虑软换行后的最长文本行的长度。它小于或等于段落的宽度。

enter image description here

最大内在宽度

如果有选择,这是段落想要的宽度。如果没有软换行,它就是最长行的宽度。也就是说,如果“A line of text that wraps around.”没有被强制换行,它的宽度就是最大内在宽度。

enter image description here

最小内在宽度

这是段落可以不用强制断词就能达到的最窄宽度。您可以在下面的示例中看到,minIntrinsicWidth是单词“Another”的宽度。

enter image description here

补充代码

如果您想自己试玩,请创建一个新的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;
  }
}

另请参阅


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接