加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 02:14:02 所属栏目:百科 来源:网络整理
导读:我正在使用arrayCollection字符串填充dropDownList.我希望下拉列表控件的宽度与数组集合中最长字符串的大小(以像素为单位)匹配.我面临的问题是:集合中字符串的字体宽度不同,例如: ‘W’看起来比’l’宽.所以我估计一个字符的宽度是8像素,但这不是很整洁.如
我正在使用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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读