tags:

views:

47

answers:

1

I'm wondering if I can dynamically embed fonts in Flex. I want to embed different fonts for different users so I don't want to embed all possible fonts in the same Flex file. If it's possible could you please post sample code.

+1  A: 

You can do this in Actionscript. I've used this trick primarily to use opentype fonts that weren't supported with the compiler in the Flash IDE and to create font libraries that could be loaded lazily (only when needed), but you can also use this to selectively load fonts. If you had the mxmlc compiler on your server you could even generate the fontlib.as file and compile it on command.

// fontlib.as
// font library file
package {
   import flash.display.Sprite;

   public class fontlib extends Sprite {
      [Embed(source = 'font/path/FontFile.otf', fontName = 'FontFile', unicodeRange = 'U+0020-U+007E,U+00AB,etc...')]
      public static var FontFile:Class;
      public static const FontFile_name:String = "FontFile";  // matches 'fontName' in embed

      public function fontlib() {
      }
   }
}

This can be compiled like so:

mxmlc fontlib.as

You can use in your application like this:

// Main.as
// document class
package {
   import flash.text.Font;
   import flash.display.Loader;
   import flash.events.Event;
   import flash.system.ApplicationDomain;
   import flash.text.StyleSheet;

   public var fontsLoader:Loader;
   public var fontFile:String = "";
   public var ss:StyleSheet;

   public function Main() {
      fontsLoader = new Loader();
      fontsLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, _onFontsLoadComplete);
   }

   private function _onFontsLoadComplete(e:Event):void {
      var fontlib:Class = e.target.applicationDomain.getDefinition('fontlib');

      Font.registerFont(fontlib.FontFile);  // registers font
      fontFile = fontlib.FontFile_name;     // name the font was loaded as

      // actually using the font looks like this:
      ss = new StyleSheet();
      ss.parseCSS("div { fontFamily: " + fontFile + "; }");
   }
}
David Woods