如何知道TextWidget将包装的位置?

时间:2018-01-28 19:15:56

标签: flutter

当使用带有大字符串的Text窗口小部件时,会发生显示的文本在2行或更多行上拆分。

我的问题很简单:如何知道字符串分割的确切字符?

我已经挖掘了Text代码内部。最多dart:ui' Paragraph。但我还没有找到任何可用的东西。

1 个答案:

答案 0 :(得分:1)

实际上,flutter中的文本使用TextPainter在画布上绘制,{{3}}在运行时使用其父类的框约束来计算布局大小。如果您已经知道可用空间,则可以计算文本的布局宽度,并将其与可用宽度进行比较,以了解文本的中断位置。

您可以使用TextPainter计算文字的宽度,如:

final TextPainter paint = new TextPainter(
  text: new TextSpan(
    text: "Hello World",
  ),
  textDirection: TextDirection.ltr
);
paint.layout();
debugPrint(paint.width.toString());

您也可以使用CustomPainter这样做:

import 'package:flutter/material.dart';

void main() {
  String text = "Hello World";

  void textShownOnUI(int size){
    debugPrint(text.substring(0,size));
  }

  runApp(new MaterialApp(
    title: "Example",
    home: new Container(
      width: 100.0,
      padding: const EdgeInsets.all(175.0),
      child: new CustomPaint(
        painter: new MyTextWidget(
          text: text,
          style: new TextStyle(),
          notifySize: textShownOnUI
        ),
        child: new Container(),
      ),
    ),
  ));
}

class MyTextWidget extends CustomPainter {

  Function notifySize;

  String text;

  TextStyle style;

  TextDirection direction;

  MyTextWidget({this.text,this.notifySize,this.style,this.direction});

  @override
  void paint(Canvas canvas, Size size){
    debugPrint(size.width.toString());
    final TextPainter _painterWithConstrains = new TextPainter(
      text: new TextSpan(
        text: text,
        style: style
      ),
      textDirection: direction??TextDirection.ltr
    );
    String _willBeShownOnUI = text;
    int _size = text.length;
    TextPainter _temp = new TextPainter(
        text: new TextSpan(
            text: _willBeShownOnUI,
            style: style
        ),
        textDirection: direction??TextDirection.ltr
    );
    _painterWithConstrains.layout(maxWidth: size.width);
    _temp.layout();
    while(_temp.width > _painterWithConstrains.width && _size != 0){
      debugPrint(_temp.width.toString()+"  "+ _size.toString());
      _willBeShownOnUI = _willBeShownOnUI.substring(0, --_size);
      _temp = new TextPainter(
          text: new TextSpan(
              text: _willBeShownOnUI,
              style: style
          ),
          textDirection: direction??TextDirection.ltr
      );
      _temp.layout();
    }
    _size = _willBeShownOnUI.split(" ")[0].length; // Get complete words that will be shown
    Function.apply(notifySize,<int>[_size]);
    _painterWithConstrains.paint(canvas, Offset.zero);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

希望有所帮助!