flutter-计算字体大小

///计算文本大小
Size calculateTextSize(
  BuildContext context, //当前界面上下文
  String value, //文本内容
  double fontSize, //文字的大小
  FontWeight fontWeight, //文字权重
  double maxWidth, //文本框的最大宽度
  int maxLines, //文本支持最大多少行
) {
//过滤文本
//   value = filterText(value);
//防呆
  if (value == null || value.isEmpty) {
    return Size.zero;
  }
//TextPainter
  TextPainter painter = TextPainter(
    //AUTO:华为手机如果不指定locale的时候,该方法算出来的文字高度是比系统计算偏小的。
    locale: Localizations.localeOf(context),
    maxLines: maxLines,
    textDirection: TextDirection.ltr,
    text: TextSpan(
      text: value,
      style: TextStyle(
        fontWeight: fontWeight,
        fontSize: fontSize,
      ),
    ),
  );
//设置layout
  painter.layout(minWidth: maxWidth);
//文字的Size
  return painter.size;
}
///计算文本大小
Size boundingTextSize(
  BuildContext context, //当前界面上下文
  String text, ////文本内容
  TextStyle style,
  int maxLines, //文本支持最大多少行
  double maxWidth, //文本框的最大宽度
) {
  //防呆
  if (text == null || text.isEmpty) {
    return Size.zero;
  }
  //TextPainter
  final TextPainter painter = TextPainter(
    //AUTO:华为手机如果不指定locale的时候,该方法算出来的文字高度是比系统计算偏小的。
    locale: Localizations.localeOf(context),
    maxLines: maxLines,
    textDirection: TextDirection.ltr,
    text: TextSpan(text: text, style: style),
  );
  //设置layout
  painter.layout(maxWidth: maxWidth);
  //文字的Size
  return painter.size;
}

参考:
//www.greatytc.com/p/cc3e6f78c85d
//www.greatytc.com/p/f713e5a36da5

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容