gpt4 book ai didi

以像素为单位的字符串长度抖动

转载 作者:行者123 更新时间:2023-12-03 02:47:40 24 4
gpt4 key购买 nike

我有一个字符串( '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;
}
}
enter image description here

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com