字符串长度(以像素为单位)

时间:2019-06-14 09:32:08

标签: string flutter dart

我有一个字符串('hello')和一个字体大小(20),是否有任何方法可以给我以像素为单位的字符串长度?

final String foo = 'hello';
final double fontSize = 20.0:
final pix = pixelsOf(foo, fontSize); //something like this

1 个答案:

答案 0 :(得分:1)

这是示例代码:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: Scaffold(body: Home())));
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var text = 'I\'m awesome!';
    var size = calcTextSize(text, TextStyle(fontSize: 20));

    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(text, style: TextStyle(fontSize: 20)),
          Container(width: size.width, height: 4, color: Colors.blue),
          Text(size.width.toString()), // this blue line has exactly same width as text above
        ],
      ),
    );
  }

  Size calcTextSize(String text, TextStyle style) {
    final TextPainter textPainter = TextPainter(
      text: TextSpan(text: text, style: style),
      textDirection: TextDirection.ltr,
      textScaleFactor: WidgetsBinding.instance.window.textScaleFactor,
    )..layout();
    return textPainter.size;
  }
}

enter image description here