Length of a string in pixels

前端 未结 4 1124
借酒劲吻你
借酒劲吻你 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:21

    This is a more polished version of some of the above code. Accounting for linebreaks (html break and \n) and nullifying the created Textfield object with some other optimizations. Hope this is helpful.

    function measureString(str:String, font:String="Times New Roman", size:Number=12):Rectangle 
    {
        var textField:TextField = new TextField();
        textField.defaultTextFormat = new TextFormat( font, size );
        textField.border = true;
        textField.multiline = true;
        textField.autoSize = TextFieldAutoSize.LEFT;
        textField.htmlText = str;
        // Grab with and height before nullifying Textfield.
        var w:Number = textField.textWidth;
        var h:Number = textField.textHeight;
        //addChild( textField );// This will add the Textfield to the stage so you can visibly see it.
        //if( contains( textField ) ) removeChild( textField );// If it exists onstage, remove it.
        textField = null;//nullify it to make it available for garbage collection.
        return new Rectangle(0, 0, w, h);
    }
    
    var str:String = "Jeremy is a good boy.
    He also has a red bike. \nSometimes Jeremy rides his bike to the store to buy bread for his family.
    He likes wholewheat."; trace( measureString( str, "Times New Roman", 25 ).width );

    If you prefer this in a class, check it out in my GIT framework: https://github.com/charlesclements/as3-tools/blob/master/net/charlesclements/util/text/TextUtil.as

    AS3-tools:https://github.com/charlesclements/as3-tools

    Also, our Flash/JS brother Jack Doyle @ GreenSock has some handy stuff to do with manipulating text. Well worth it to check it out:http://www.greensock.com/splittext/

提交回复
热议问题