Tuesday, 17 January 2012

How to Format Text in Actionscript III

In the last article I've shown you a way to embed fonts in Actionscript. That process implies that you will have to embed the font on your compiled and final SWF file. This means that you final SWF will increase, and in some cases dramatically, because you are making the fonts you want to use available in your compiled code.

At this project that I'm working on, this is something we can't do, due to limitation on the hardware we're using. And beacuse the skinning of the application can change, so the fonts can be changed also.

For this purpose we use font embedding but, the fonts will be stored in external, and dedicated SWF files.

To start this process, a first step is to make a SWF file just for the font:
- Open a new FLA file in Flash;
- Place the following code in the first and empty frame of the timeline:

[Embed(source='ARIAL.TTF', fontName = 'Arial', mimeType="application/x-font", unicodeRange="U+0020-U+007E")]
var arial:Class;


This code is explained in the previous article. So if you came here directly and don't understand what's in here, just go there and see what this means.

This SWF will only have the embed characters you tell on the unicodeRange. So if you use any other characters with this font, they won't appear. So make sure your character range is correct.

Compile the file and place it on your local folder or in a "fonts" folder. In this case I will call it arial.swf.

To use this in your code just to simply something like this:
- In your AS3 class define a new Loader variable to keep to load the font:

private var fontLoader:Loader = new Loader();

- Load the font in the main constructor, or wherever it may suit your needs like this:

fontLoader.load(new URLRequest("sections/swfs/fonts/arial.swf"));

- After this, whenever you want to use the font in a textField you need to use the TextFormat to assign this font and change text appearance, like this:

var myText:TextField=new TextField();

myText.defaultTextFormat = new TextFormat("Arial", 38, 0x2DAAFD, true);
myText.selectable = false;
myText.text = "Hello World!";

NOTE: In the TextFormat, "Arial" is the name you gave the font in the Embed in the font SWF file.

This method makes easier to use and change fonts dynamically, for example defining a font to be used in a textField through an XML file.

Happy coding!