Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating Text Width In ActionScript And Flex

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.

like image 810
Joshua Avatar asked May 26 '10 21:05

Joshua


4 Answers

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.

like image 67
quoo Avatar answered Nov 19 '22 18:11

quoo


This works any format, size, font type. Don't forget properties "autoSize" and "wordWrap"!

var tf:TextField = new TextField();
addChild(tf);
tf.autoSize = TextFieldAutoSize.LEFT;
tf.wordWrap = false;
tf.text = "Whatever here";
tf.width = tf.textWidth + 4; // add 2 pixels-gutters left & right

Your button will need to be "tf.width" wide...

like image 9
Simmoniz Avatar answered Nov 19 '22 18:11

Simmoniz


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; 
like image 2
Thomas Brady Avatar answered Nov 19 '22 16:11

Thomas Brady


Here's a way that works also:

var tempText:Text = new Text();
tempText.regenerateStyleCache(false);
var textWidth:int = tempText.measureText(*yourstring*).width;
like image 1
Bly Avatar answered Nov 19 '22 17:11

Bly