Paragraph.getBoxesForRange 在 Flutter 中实际得到了什么

What does Paragraph.getBoxesForRange actually get in Flutter

Flutter 中的class 段有一个名为getBoxesForRange 的方法。

documentation 说:

Returns a list of text boxes that enclose the given text range.

但是,我不清楚这些框是包含给定范围的文本行周围的框,还是其他内容。

经过进一步研究,我找到了答案,我将其添加到下面。

简答

Paragraph.getBoxesForRange 为您提供了给定范围的突出显示区域(如果它被选中)。如果范围换行(或者如果它包含混合双向文本),您会得到多个框。

更长的答案

给定字符串:

Hello, world.

如果您采用从 18 的范围,如下所示:

final boxes = paragraph.getBoxesForRange(1, 8);

这会给你一个盒子:

[
  TextBox.fromLTRBD(22.3, -0.3, 112.0, 35.0, TextDirection.ltr)
]

图形表示如下:

这表明方框不是整行,而是只环绕指定的文本范围。

如果您限制宽度以强制段落换行,您将得到以下内容:

[
  TextBox.fromLTRBD(22.3, -0.3, 47.0, 35.0, TextDirection.ltr), 
  TextBox.fromLTRBD(0.0, 34.7, 41.8, 70.0, TextDirection.ltr), 
  TextBox.fromLTRBD(0.0, 69.7, 23.2, 105.0, TextDirection.ltr)
]

完整代码

如果您想自己尝试一下,这里是完整代码。

import 'package:flutter/material.dart';
import 'dart:ui' as ui;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: HomeWidget(),
      ),
    );
  }
}

class HomeWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: CustomPaint(
        size: Size(300, 300),
        painter: MyPainter(),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final textStyle = ui.TextStyle(
      color: Colors.black,
      fontSize: 30,
    );
    final paragraphStyle = ui.ParagraphStyle(
      textDirection: TextDirection.ltr,
    );
    final paragraphBuilder = ui.ParagraphBuilder(paragraphStyle)
      ..pushStyle(textStyle)
      ..addText('Hello, world.');
    final constraints = ui.ParagraphConstraints(width: 300);
    // final constraints = ui.ParagraphConstraints(width: 50);
    final paragraph = paragraphBuilder.build();
    paragraph.layout(constraints);
    canvas.drawParagraph(paragraph, Offset.zero);

    final boxes = paragraph.getBoxesForRange(1, 8);
    print(boxes);
    final paint = Paint()
      ..color = Colors.blue
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;
    for (final box in boxes) {
      final rect = Rect.fromLTRB(box.left, box.top, box.right, box.bottom);
      canvas.drawRect(rect, paint);
    }
  }

  @override
  bool shouldRepaint(CustomPainter old) {
    return false;
  }
}