Set button width to text width in flex

Well, I have been working on a very interesting project recently, really stretching flex to the limits :-)

I needed to set buttons, linkButtons, Labels and more components width to the width of the text inside them.

Usually, flex does it for you, but the width was hardcoded in compile time and I needed to change the text and the width in runtime and resize the component according to that.

I have written a nifty helper function for that.

Here it is:

[as3]

/**

*

*/

public static function measureTextWidthAndResizeComponent(text:String, container:UIComponent):void

{

var _measuredWidth:Number = 0;

var _paddingLeft:uint = 0;

var _paddingRight:uint = 0;

var _horizontalGap:uint = 0;

var _addedToWidth:int;

if(text == null)

return;

if(text.length <= 1)

return;

_paddingLeft = container.getStyle(“paddingLeft”);

_paddingRight = container.getStyle(“paddingRight”);

_horizontalGap = container.getStyle(“horizontalGap”);

_addedToWidth = int(_horizontalGap + _paddingLeft + _paddingRight);

var lineMetrics:TextLineMetrics = container.measureText(text);

_measuredWidth = (lineMetrics.width + _addedToWidth);

container.width = _measuredWidth;

}

[/as3]

That’s it, enjoy!

Submit to Hacker News

[NOTE] This post has been imported to Hugo from a Wordpress blog. It may be broken, missing images, code snippets or other information.

[NOTE] updated July 14, 2010. It's 3120 days old . This article may have outdated content.