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

前端之家收集整理的这篇文章主要介绍了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);

猜你在找的Flex相关文章