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

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

最佳答案

这是示例代码:

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;
  }
}
string - 字符串长度(以像素为单位)-LMLPHP

关于string - 字符串长度(以像素为单位),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56595325/

10-10 08:15