Tuesday, 17 January 2012

How to Format Text in Actionscript II

Some time ago I posted a way to format text using the fonts available in your system that you should, in the first place, import to your library and then use it on your code.

Meanwhile I had a new project where I was asked to come up with a way to use fonts. This project is to be embeded in a set top box, so there's a limitation about the fonts you can use. That's if the box has any available for you to use.

In this case there's no font I can use, so I have to "install" my fonts on the box in order to Flash to recognize them.
Another limitation is that the software can use a font, and I mean any font, that the Design department comes up with. This means that at some point I can have more or less fonts installed on the system. If we can't install fonts on the box, how can I use fonts as I please?

There's two possible answers for this:

One is using a Flex approach using the Embed tag. In you Actionscipt class, where you define your global variables put something like this:

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

As a brief explanation:
- The source must be a font file already in your local folder;
- The fontName is the name you  will call in your code when you want to use the font;
- The mimeType is just something you have to write in order for the compiler to know that this is a font file;
- The unicodeRange is very important because it gives you the possibility of embedding just the characters you want in unicode. In this case "U+0020-U+007E" means a-Z (a to z in lower and uppercase).

For more details about the characters code to use, visit http://unicode.org/charts/ or http://www.rishida.net/tools/conversion/ that will make the conversion for you.

The var arial:Class must come after the Embed tag so that this font instantiated and can be used in the code you make.

For this you'll have to make a final step, which is: In the constructor of you class, register the font using this line of code

After this whenever you want to use this font just to something like this:

var myTextBox:TextField = new TextField();

myTextBox.defaultTextFormat = new TextFormat("Arial", 38, 0x2DAAFD, true);
myTextBox.selectable = false;
myTextBox.text = "My text in Arial";

The "Arial" in new TextFormat("Arial", 38, 0x2DAAFD, true); is the name you gave to the font in the Embed tag, the rest is size, color and whether is bold or not.

The downside of this method is that if you want to use several fonts, you will have to embed them in the code, which mean that you will have to compile each time you change, add or delete a font from the code.

In my case this has to be more dynamic.

The next article will show how you can embed the font through a separate SWF file with the font in it. Just click here to go there.

Happy coding!