Tuesday, September 30, 2008

You have a flash / flex application where you want to allow users to customize the text formatting, font style / font weight for some text box. So you would provide a small set of fonts which would all get embedded into the swf.

If we working with external fonts in Actionscript 3.0, the external font must have a class definition for allowing the Font class and ApplicationDomain to detect and register it. We can produce class definition for the external font with embed tag in Flex or Font symbol in Flash library.

In Flash CS3 you can create a font symbol in the library, and export it for ActionScript. But with this way if you embed the font in the library then flash automatically embeds all available characters. So the compiled external font swf size will increased and bloated the load-time with unused fonts. This was the largest issues especially if we working with Asian fonts. You can find more informations about it in this nice article

With Flex 3.0 and mxmlc (Flex SDK 2-3) there’s the embed metatag where you can even define font character ranges which should be embedded for reducing compiled external font swf size:

Unfortunatelly if we combining subset tag (unicodeRange) with fontWeight / fontStyle tag will cause a Flex compile error. I hope in Flex 4 this issue fixed.

This article explain the same approach, but it need to add extra font family (Bold or Italic) at specific font but Flex will still treat them as separate fonts.

All the examples (both Flash CS3 or Flex 3.0) I’ve seen so far only address the loading of one font either in regular weight or bold, but not one (subset characters ranges) fonts with regular, weight, italic or bold-italic at the same time. And it seem very difficult for export one (subset characters ranges) font as external font, (ie loading the font from an external swf) and change font weight / font style at runtime in loader (main app) swf.

Luckily I was able make something worked, here what I did :

Embed font in FLA file with instance textfield at the stage (Benefit: we can make subset of required glyphs only, and font style/weight). We need create four instances textfield (Regular, Bold, Italic and Bold-Italic texfield) and publish the swf for each font, (ie. Verdana_Style.swf for Verdana). In this step the published swf doesn’t contain class definition yet. So we can not import it at runtime.

Transcoding the published swf (also give a class definition) with Flex 3.0 compiler with Embed metatag and publish to final external swf font (i.e Verdana.swf)