gpt4 book ai didi

actionscript-3 - 字符串的长度(以像素为单位)

转载 作者:行者123 更新时间:2023-12-04 07:44:44 24 4
gpt4 key购买 nike

我正在用字符串的 arrayCollection 填充 dropDownList。我希望下拉列表控件的宽度与数组集合中最长字符串的大小(以像素为单位)相匹配。我面临的问题是:集合中字符串的字体宽度不同,例如'W' 看起来比 'l' 宽。所以我估计一个字符的宽度是 8 像素,但这不是很整洁。如果遇到一个包含许多 'W' 和 'M' 的字符串,则估计是错误的。所以我想要字符串的精确像素宽度。如何以像素为单位获得字符串的确切长度?

我估计所有字符为 8 像素宽的解决方案如下:

public function populateDropDownList():void{
var array:Array = new Array("o","two","three four five six seven eight wwww");
var sampleArrayCollection:ArrayCollection = new ArrayCollection(array);
var customDropDownList:DropDownList = new DropDownList();
customDropDownList.dataProvider=sampleArrayCollection;
customDropDownList.prompt="Select ...";
customDropDownList.labelField="Answer Options:";
//calculating the max width
var componentWidth=10; //default
for each(var answerText in array){
Alert.show("Txt size: "+ answerText.length + " pixels: " + answerText.length*9);
if(answerText.length * 8 > componentWidth){
componentWidth=answerText.length * 8;
}
}
customDropDownList.width=componentWidth;
answers.addChild(customDropDownList);
}

任何想法或解决方案都受到高度重视。

谢谢

最佳答案

要获得更准确的测量值,您可以使用字符串填充 TextField,然后测量该 TextField 文本的宽度。

代码:

function measureString(str:String, format:TextFormat):Rectangle {
var textField:TextField = new TextField();
textField.defaultTextFormat = format;
textField.text = str;

return new Rectangle(0, 0, textField.textWidth, textField.textHeight);
}

用法:
var format:TextFormat = new TextFormat();
format.font = "Times New Roman";
format.size = 16;

var strings:Array = [ "a", "giraffe", "foo", "!" ];

var calculatedWidth:Number = 50; // Set this to minimum width to start with

for each (var str:String in strings) {
var stringWidth:Number = measureString(str, format).width;
if (stringWidth > calculatedWidth) {
calculatedWidth = stringWidth;
}
}

trace(calculatedWidth);

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

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