I guess the topic of dynamically loading fonts in Flash swfs is fairly old by now, and has been covered by several other people. But this was always something I meant to write up so … better late than never? I should say that while the way I did it back in the day works, Flex offers a few short cuts over a Flash IDE only approach. Anyway this is my take on the subject and is what I used when I was building the Flash albums for Zoto.
The first step is to get the fonts into a form flash can work with. This is done by wrapping the desired font inside its own swf file. Create a new .fla, and embed the desired font into the library. Mark its linkage to export for ActionScript
and to export in the first frame. Finally, publish the swf.
To use the font at runtime, load the published font swf into your movie via a Loader. Now for the tricky part. Once the loader is complete we need to get a reference to the embedded font and register it with the Font class. Do this like so where [fontname] is the name of the font you embedded into the loaded swf:
var f:Class = loader.contentLoaderInfo.applicationDomain.getDefinition(<em>fontname</em>) as Class; Font.registerFont(f);
Almost finished. The last step is to get the actual font name from the loaded font as this can be different from the name of the font class when you embedded it. To do this, create an instance of the font get its fontName property like so:
var inst:Font = new f(); var fontName:String = inst.hasOwnProperty('fontName') ? inst.fontName: '';
You can now use the dynamically font with a TextField by setting the TextField’s embedFonts property to true and setting its TextFormat to use the loaded font’s name:
var tf:TextField = new TextField(); tf.defaultTextFormat = new TextFormat(fontName, 12, 0); tf.embedFonts = true;
Dynamically loading fonts at runtime is a great way to keep the text in your swf’s customizable and keep the file size down. However, I suppose it should go without saying that you should be careful about using this trick with licensed/proprietary fonts. Unless you are law-savvy on what counts as unauthorized distribution/sharing it might be best to stick with free fonts with this trick.
Add a Comment: