Friday, 16 October 2009

How to Format Text in Actionscript

This time I will post a snippet about how to format text in a textfield that is placed dynamicaly in the Stage.


Firstly you must insert the TextField on the stage. For that you need to place these two line in order to import the class that controls the TextField object in AS3. The second import, will import the class that control the appearence of TextFields:



import flash.text.TextField;
import flash.text.TextFormat;

Next you need to create the TextField and place it in the DisplayObject list:

var myText:TextField = new TextField();
addChild(myText);

Next you can tell Flash if the user can select the text, and if you want some border around the TextField:



myText.selectable = false;
myText.border = false;


Next you can tell if the TextField is autosizable, that is, if the text inside is to be dynamic, maybe you need the TextField to stretch or shrink, according to the text value. You can even tell if the autosize is to the right, center or left:


myText.autoSize = "center";


Now we're ready to format the contents of the TextField. For that you need to create a TextFormat object that will be associated to the TextField later on.


Create the TextFormat object:


var myFormat:TextFormat = new TextFormat();


Define the font face you want to use. Then you can define if the text is to bold, underline or italic:


myFormat.font = "Myriad Pro";
myFormat.bold = true;


Give it some colour:


myFormat.color = 0xFF0000;


Change the size:


myFormat.size = 12;


Finally associate the TextFormat to the TextField:


myText.setTextFormat(myFormat);


Happy Texting...