Working with text in Flash can be a painstaking procedure, especially if you just want to quickly draw and animate some simple characters on screen using ActionScript. It usually takes many lines of codes to setup and adjust the appearance and alignment of text fields and you need to take care of other little annoying details like the whole font embedding procedure.
Lately I was working on a new interactive testbed for the motor physics engine where I’m solely using the new flash player 10 vector drawing API, but I needed to add some text. I was curious about how hard it would be to add text rendering capabilities to the drawing API and after some investigation I found an easy way using an old copy of Fontographer to extract the necessary data from a true type font file (much easier than trying to parse a .ttf file directly):
- Export the font data as an EPS postscript file.
- Write a parser to transform each glyph into a bunch of lineTo, moveTo and curveTo commands.
- Export and parse the spacing and kerning table (proportional fonts only).
- Write a method for drawing cubic bézier curves.
Following these steps I ended up with a simple text rendering engine. Here my result:
Monospace/Proportional font rendering (Consolas/Arial)
As you see small font sizes won’t be that sharp and readable as a TextField set to “Anti-alias for readability” but on the other hand the results are very smooth and perfect for animation. Placing and aligning text blocks is also much easier since it’s straightforward to compute bounding boxes for glyphs and text blocks.
So now drawing a text is a matter of writing:
... graphics.beginFill(0, 1); new Arial(10.0).print("Hello World", 100, 100); graphics.endFill(); ...
This will draw “Hello World” at x,y=100,100 and a font size of 10 points. KISS!
An exciting thing is that the FP10 drawing API is actually very fast; the following demo scrolls all ASCII characters back and forth. Press space to toggle between regular text field and vector rendering. In the first case a TextField object is created once and then moved by adjusting its position, whereas in the second case the whole text is redrawn in every frame at a new position:
TextField vs. Graphics
If (hopefully) more people besides me find this useful I would invest some extra time to polish the code and publish it as open source. It made my coding life simpler :-)