header banner
Gradatim vincimus
nav

Actionscript/Flex Font Library

In search of a method to embed fonts into an Actionscript project I came across many posts out there touting the ability to embed fonts into an Library or SWC and use them across multiple projects. After many attempts using the various methods I wasn't pleased and couldn't get things to work. So in an all out effort I combined them all and suddenly everything worked

  1. Within Flex first create the Flex Library Project - I have called this FontLib
  2. Create folders within the project called assets/fonts as a place to store the fonts you want to embed
  3. Create a file within the main src package - I have called this Fonts.as
  4. Within this file I have put the code:
    Fonts.as
    package 
    {	
    	import mx.core.FontAsset;
     
    	public final class Fonts
    	{
     		//repeat this block for each font renaming the font each time
    		public static var fontLib:Array = new Array;
    		[Embed(source="../assets/fonts/testFont.ttf",
    			fontName="testFont",
    			mimeType="application/x-font-truetype")]
    		private static var TestTTF  : Class;
     		//assign the font a public static attribute
    		public static var testFont:FontAsset = new TestTTF();
    		//append the font to the fontLib list
    		fontLib.push(testFont);
    	}
    }
  5. Let that build
Now you have a library and .swc with a font embedded. You can reference the list of fonts embedded via the fontLib array or referening them by their static name (testFont)
Then to actually use the font start a new project and when you get to build settings in the Library Path tab either link to the Library you created that includes the fonts or link to the .swc file. In your Actionscript file you can link to the font as a TextFormat as:
var tf:TextFormat = new TextFormat(Fonts.testFont.fontName,22,0x000000);
 
Note the Fonts.testFont.fontName - Fonts is the name of the class created in the above steps, testFont is the static name of the font I embedded and fontName is a function of the mx.core.FontAsset class to retrieve the font name as a String for use in things like TextFormat or setStyle function if wanting to use CSS. 

The attached files are copies of projects I built for Flash Builder 4 (BETA) to demonstrate this idea - Download here

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may use <swf file="song.mp3"> to display Flash files inline

More information about formatting options