How to embed fonts using actionscript 3

This was causing my to bang my head for a little while. There are different ways depending on  whether you are using Flash or Flash Builder (previously Flex Builder). If you are using Flash you can go here for a good example/tutorial: http://www.adobe.com/devnet/flash/quickstart/embedding_fonts/. Basically you add a font to the library by clicking the pop-up menu (in the upper-right corner of the Library panel), export it for actionscript and then give it a class name. After that your code looks something like this:

var myFont:Font = new Font1();
var myFormat:TextFormat = new TextFormat();
myFormat.font = myFont.fontName;

Embedding fonts in AS3 seems to be a big problem for many people out there especially if you are using Flash Builder/Flex Builder. I know it was driving me crazy! I was following the examples, but still seemed to keep getting the same error: “An Embed variable must not have an existing value.”. Okay maybe it’s just me but that one was a little cryptic. Finally after a long time, but before having to do a Google search for straight jackets I figured out what I was missing. In all of the examples the embed line was right above a Class variable, but mine was not, so I added one and  cha ching it worked. Here is a sample:

[Embed(source="assets/MONACO.TTF", fontName="monaco",
mimeType="application/x-font-truetype")]
private var MonacoFontEmbed:Class;

It may just be me but this was not obvious I must confess. You don’t use that variable at least I didn’t, you simple set the .font property to the fontName value. It looks something like this:

myFormat.font = "monaco";

monaco is what I named it. You can name that whatever you want along with the variable. I named it MonacoFontEmbed, but you can name it whatever. I hoped this helped. If you have any questions feel free to post them. Embedding fonts is very useful especially if you are planning to manipulate a text field. Manipulations like rotation will just cause your text field to disappear if created dynamically and without embedding the font.

Leave a Reply

Your email address will not be published. Required fields are marked *