Sunday, November 1, 2009

Applying TextFormat in AS3

Let’s say you wanted to apply a TextFormat to a TextField with the setTextFormat method and you script the following code in AS3

var t:TextField=new TextField();
var tf:TextFormat=new TextFormat();
tf.font="Verdana";
tf.size=24;
tf.bold=true;
tf.color=0xff0000;
t.width=160;
t.setTextFormat(tf);
t.text="test text";


To your surprise, the resultant text does not get the textFormat you applied. The result is




Do not panic. Just swap the last two lines of code like below.

var t:TextField=new TextField();
var tf:TextFormat=new TextFormat();
tf.font="Verdana";
tf.size=24;
tf.bold=true;
tf.color=0xff0000;
t.width=160;
t.text="test text";
t.setTextFormat(tf);


And everything’s fine.




If you were to set the text once again with, say, t.text=”Another text”, you should apply the desired TextFormat once again with the SetTextFormat method. This is because every time you set the ‘text’ property of a TextField, it is the DefaultTextFormat which will be applied.

In fact if you were doing quite a bit of text handling, you are better off setting the DefaultTextFormat of the TextField with the following code

t.defaultTextFormat=tf;

No comments:

Post a Comment