Archive for May, 2009

Load font dynamically on runtime

Wednesday, May 6th, 2009

Sometimes you want to be able to keep your fonts in a seperate swf file, a “font library” if you will, that you can load dynamically on runtime. Here’s how to do that in AS3:

The first thing you have to do is create a new flash file to store the font(s). Then, right click the library and select “New Font…”.
newfont

Choose the font you want to embed and give it a name. Any name will do here, as this is only the library name and will not affect our code in any way. I prefer to name the font with the same name as the linkage name I plan to give it.
myfont

Click ok, and then right click the font in the library and select “Linkage…”. Check the “Export for ActionScript” and “Export in first frame” options, give your font the linkage name of your own liking and click OK.
linkage

And now you’re ready. Export the file to swf and there’s your font resource file.

If you want to use that font, you first have to load it into the application domain, and then register it on the global font list using the Font.registerFont function. The textfield can’t display it until it has the embedFonts property set to true and the font name in its textformat.
You can see an example in the following code, ready to be pasted into your frame:

var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
l.load(new URLRequest("MyFont.swf"), new LoaderContext(false, ApplicationDomain.currentDomain));

function onLoaded(e:Event):void {
	// Register the font to the global font list
	Font.registerFont( Class( ApplicationDomain.currentDomain.getDefinition("MyFont")));
	
	myTextField.embedFonts = true;
	// instantiate the font just to get the real font name, or if you know the name before hand you can just hard-code it in here
	var fontName:String = new (ApplicationDomain.currentDomain.getDefinition("MyFont"))().fontName;
	var tf:TextFormat = new TextFormat(fontName);
	// Set the text format for the text already in the text field
	myTextField.setTextFormat(tf);
	// and for future changes
	myTextField.defaultTextFormat = tf;
}