views:

131

answers:

2

I'm building text balloons to display variable length messages in Flash. My question is pretty simple, though the answer may not be.

I have:

  • The string I want to display.
  • The font information.
  • The width/height ratio I want the text field to have.

How do I calculate the width and height of the text field it needs to display the text I give it, nothing more, nothing less?

+1  A: 

Easiest thing I can think off is creating a textfield, setting the custom font and text then getting the size:

e.g.

var field:TextField = new TextField();
field.defaultTextFormat = new TextFormat('Verdana',12,0xDEDEDE);
field.text = 'someText';
trace(field.textWidth + ' / ' + field.textHeight);

textWidth and textHeight should give you the right numbers, as opposed the width and height properties. If you need more details than this, have a look at the TextLineMetrics class.

HTH, George

George Profenza
That would work. I need the text to span multiple lines, but I can calculate that. (TW / lines) / (TH * lines) = WHRATIO. Then field width = TW / lines
Bart van Heukelom
The solution: lines = sqrt((width/height)/ratio)
Bart van Heukelom
A: 

if you turn on autoSize it should adjust the height of your text field for you. You can then just get the height using the same field.textHeight

var field:TextField = new TextField();
field.autoSize = "left";
field.multiline = true;
field.defaultTextFormat = new TextFormat('Verdana',12,0xDEDEDE);
field.text = 'someText';
trace(field.textWidth + ' / ' + field.textHeight);
David Morrow
I thought about the same. But there is a difference between textWidth and the textField width. TextLineMetrics class that George Profenza pointed in his answer if really good to understand better this problem.
dome
I am using autosize, but I still need to set the correct width to achieve a text field with the width/height ratio I want.
Bart van Heukelom