Embedding fonts in ActionScript 3, using Flex SDK

Say you have a class and you want to use an embedded, non-system font in the class. That way you can rotate, scale, change alpha and apply filters to the text. And this is how it would look like, roughly:


public class MyClass extends Sprite
{
    [Embed(source="./../assets/MyFontLightItalic.TTF", fontFamily="MyFontFamily", fontWeight= "light", fontStyle = "italic", mimeType="application/x-font-truetype")]
    private var MyFont:Class;

    public function MyClass()
    {
        var tf:TextField = new TextField();
        tf.embedFonts = true;
        tf.defaultTextFormat = new TextFormat("MyFontFamily", 17, 0x7F7F7F);
    }
}

You might also need to make sure you're linking to framework.swc, or otherwise you will get some strange errors like Error: The definition of base class FontAsset was not found.

Interesting stuff

Because most of the examples out there simply use "Arial" as font, they will never get the myriad errors I was getting, such as "Error: exception during transcoding: Font for alias 'Blah Blah Light Italic' with plain weight and style was not found" or the much dreaded "Error: java.lang.Integer cannot be cast to java.lang.String".

The problem is that there are more sophisticated True Type Fonts out there, which split the font in several files, one for each variation of weight and style, and if you try to embed a file for a non normal weight, normal style, the Flex compiler won't be able to find the definition of the shapes for the "normal version" and then will simply stop and let you wondering why it doesn't work.

So that's why we're specifying not only the source file but also the weight and style of the font, and that's what most of the examples never deal with -- because Arial comes as a single file.

Then there's the other important thing: the private class to which the font file will be attached. Even if you simply use the embedded font with the new alias defined in fontFamily ("MyFontFamily" in this example), you still need to provide that variable, or you will get a big "Error #2136: the swf file contains invalid data".

More info

I assembled the solution to my woes taking parts from several sources: