Calculating Text Width In ActionScript And Flex

Joshua picture Joshua · May 26, 2010 · Viewed 24k times · Source

I'm trying to calculate how WIDE to make my button, based on the text that it will contain, and when I try to google for how to calcuate something as simplistic as the WIDTH OF SOME TEXT, I go cross-eyed just trying to wade through apparently nonsensical esoteric counter-intuitive voodoo. Can anyone out there help simplify for me how I would write a function like this:

public function HowWideWouldThisTextBeIfItWereInThisButton(Text:String,Container:Button):int {
 ...
}

Thanks in advance.

Answer

quoo picture quoo · May 26, 2010

So long as you're in a UIComponent, you can use the measureText function.

public function howWideWouldThisTextBeIfItWereInThisButton(text:String,container:Button):int {
   var lineMetrics:TextLineMetrics = container.measureText(text);
   return lineMetrics.width;      
}

That being said, the flex button component should automatically size to the width of the text, if you don't set a width on it. That way if you need the text width, you can just call use the textWidth property.