views:

488

answers:

4

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.

A: 

Sounds like you could use textWidth

Lars
How does this take into consideration the format, font, size and other attributes of the button label?
Joshua
+2  A: 

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.

quoo
I'm probably doing something wrong, but I get:TypeError: Error #2007: Parameter antiAliasType must be non-null.
Joshua
Are you setting antiAliasType?
quoo
WHAT antiAliasType? What is that? Where do I set it? Is it a part of lineMetrics? The Button?? How do I find it?
Joshua
What line number are you getting it on? The debugger should tell you what it's a property of - it's likely the button label's, but it's hard to tell w/o seeing the code. It should be set by default though to 'normal'.
quoo
A: 

Joshua, it really helps to be clear. Are you talking TextField, MX Label, Spark Label, RichText, etc? Different text components use different text engines, such as FTE and TLF and may have different solutions. I certainly wish Adobe had a good set of utilities or sample code which could predict what the size of font rendered onto the controls would be, before you actually do it. But, the good news is that in certain cases - like, a good old fashioned TextField, you can predict this pretty well. You just make a TextField, set it's textFormat field, auto size method and the text. You should be able to get it's size before adding it anywhere. I don't remember what the order was, but, I remember the order you set those properties matters. If you can't figure out how to do it, I can provide a code example. Now, for the new, "improved", components such as Spark Labels - I'll be buggered if I can find a damn way... spent a number of hours on this and haven't found a way.. or someone who knows a way :P.

Cyrus Amiri
A: 

Here's how you do it in Spark:

I've modified - simplified - his example a bit here:

var textMetrics:TextLineMetrics = label.measureText( label.text );  
var textWidth:int = textMetrics.width; 
Thomas Brady