一个串中的像素长度 [英] Length of a string in pixels

查看:132
本文介绍了一个串中的像素长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用填充字符串ArrayCollection的一个DropDownList。我想下拉列表控件的宽度与大小(像素)匹配最长字符串数组集合。我现在面临的问题是:集合中的字符串的字体宽度是不同的,例如'W'看起来比'L'宽。所以,我估计一个字符的宽度为8个像素,但是这不是pretty的整洁。如果有许多'W'和'M'的字符串时遇到的估计是错误的。所以,我想precise像素串的宽度。我怎样才能得到一个字符串的像素??确切的长度

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.

感谢

推荐答案

要获得更精确​​的测量,可以填充文本字段的字符串,然后测量该文本字段的文本的宽度。

To get a more accurate measurement, you can populate a TextField with the string, then measure the width of that TextField's text.

code:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆