Thursday, 10 February 2011

Autosize text field width in AS3

I was contacted with a question about how to auto size a text field in Actionscript 3. When you trace out the text width and height you see that the default text field dimensions are 100 x 100 pixels.

var tf:TextField = new TextField();
tf.border = true;
tf.text= 'testing ';
addChild(tf);

trace(tf.width, tf.height); //100 100


In the AS3 TextField class there are two properties called textWidth and textHeight that return the width and height of the text in pixels (not the text field dimensions). You can use these properties to set the width and height of the text field.

var tf:TextField = new TextField();
tf.border = true;
tf.text= 'testing';
tf.height = tf.textHeight;
tf.width = tf.textWidth;
addChild(tf);

For some strange reason the text width and height gets cut short by 4 pixels, but you can easily add the 4 pixels back on.

var tf:TextField = new TextField();
tf.border = true;
tf.text= 'testing';
tf.height = tf.textHeight + 4;
tf.width = tf.textWidth + 4;
addChild(tf);

Another way to set the width and height is to use the autoSize property. This will automatically size and align the text field area.

var tf:TextField = new TextField();
tf.border = true;
tf.text= 'testing123';
tf.autoSize = TextFieldAutoSize.LEFT;
addChild(tf);

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP