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

我正在使用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,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);

相关文章

一:display:flex布局display:flex是一种布局方式。它即可以...
1. flex设置元素垂直居中对齐在之前的一篇文章中记载过如何...
移动端开发知识点pc端软件和移动端apppc端软件是什么,有哪些...
最近挺忙的,准备考试,还有其他的事,没时间研究东西,快周...
display:flex;把容器设置为弹性盒模型(设置为弹性盒模型之后...
我在网页上运行了一个Flex应用程序,我想使用Command←组合键...