Length of a string in pixels

前端 未结 4 1125
借酒劲吻你
借酒劲吻你 2020-12-09 21:39

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 th

4条回答
  •  执笔经年
    2020-12-09 22:23

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

    Usage:

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

提交回复
热议问题