字符串的长度(以像素为单位) [英] Length of a string in pixels
问题描述
我正在用字符串的 arrayCollection 填充 dropDownList.我希望下拉列表控件的宽度与数组集合中最长字符串的大小(以像素为单位)相匹配.我面临的问题是:集合中字符串的字体宽度不同,例如'W' 看起来比 'l' 宽.所以我估计一个字符的宽度是 8 像素,但这不是很整洁.如果遇到包含许多 'W' 和 'M' 的字符串,则估计是错误的.所以我想要字符串的精确像素宽度.如何以像素为单位获得字符串的确切长度?
I'm populating a dropDownList with arrayCollection of strings. I want the width of the drop down list control to match with the size (in pixels) of the longest string in the array collection. The problem I'm facing is: the font width of the strings in the collection are different e.g. 'W' looks wider than 'l'. So I estimated the width of a character to be 8 pixels but that's not pretty neat. If a string that has many 'W' and 'M' is encountered the estimation is wrong. So I want precise pixel width of strings. How can i get the exact length of a string in pixels??
我估计所有字符宽度为 8 像素的解决方案如下:
My solution that estimates all character to be 8 pixels wide is given below:
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);
}
任何想法或解决方案都受到高度重视.
Any idea or solution is highly valued.
谢谢
推荐答案
要获得更准确的测量值,您可以使用字符串填充 TextField,然后测量该 TextField 文本的宽度.
To get a more accurate measurement, you can populate a TextField with the string, then measure the width of that TextField's text.
代码:
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);
这篇关于字符串的长度(以像素为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!