Thursday, June 4, 2009

FontBook: AS3 Font and CSS stylesheet management class

I developed this singleton FontBook class to function as a font and CSS stylesheet manager for flash and flex projects. It loads fonts from an external swf and registers them so they can be accessed by the parent swf and all children of the parent swf. If a CSS Path is passed into the FontBook instance, FontBook loads and parses the external css stylesheet to use with the fonts.

FontBook should be used for managing text treatment in mini-sites and other multi-page/ multi-swf applications. By keeping the fonts separate from the content swfs and only needing to load them once FontBook helps keep file sizes low.

Implementation:
  1. Open a new fla, right click in the library and select "new font"
  2. Choose the font you wish to embed. Select "export for Actionscript" and give it a class name
  3. Add as many fonts as you need
  4. In the first and only frame of the fla, open the actions panel and populate a fontClassArray array with the class names of the fonts chosen to embed (NOTE: use the class names specified in the "export for Actionscript" settings, NOT the proper font names) :

    var fontClassArray:Array = ["MyFontClassName1", "MyFontClassName2", etc, etc];
  5. Save the fla and export the swf (i.e. fonts.swf)
  6. In the target application instantiate FontBook and pass the location of the font swf and css stylesheet to the FontBook constructor.
    public var fontBook:FontBook;
    private var _cssPath:String = "stylesheet.css";
    private var _fontsPath:String = "fonts.swf";

    fontBook = FontBook.getInstance(_fontsPath,_cssPath);
    fontBook.addEventListener (FontBook.FONT_DATA_ERROR, onFontDataError);
    fontBook.addEventListener (FontBook.CSS_DATA_ERROR, onCSSDataError);
    fontBook.addEventListener (FontBook.FONTS_LOADED, onFontsLoaded);
    fontBook.addEventListener (FontBook.CSS_LOADED, onCSSLoaded);

    private function onFontsLoaded(event:Event):void
    {
    trace (Fonts.enumerateFonts()); // will trace out the embedded fonts
    }
  7. To retrieve fonts and stylesheet for use with htmlText:
    var tField:TextField = new TextField();
    tField.styleSheet = fontBook.css;
    tField.embedFonts = true;
    tField.htmlText = "<'span class="cssClass">lorem Ipsum...<'/span>"
    // where 'cssClass' is a class style in the stylesheet
  8. To retrieve fonts from FontBook for use with Flash's TextFormat:
    var tFormat:TextFormat = new TextFormat();
    tFormat.font = fontBook.fontByClass("MyFontClassName1");
    //where "MyFontClassName1" is the font class name in the fontClassArray of fonts.swf
download FontBook

1 comment:

x0x said...

This looks useful but the zip is missing. Any chance of a re-up, please?