微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);

原文地址:https://www.jb51.cc/flex/174261.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐