AS3 - Dynamic Text with Embedded Font for Nice Smooth Text , Animation, Rotation, Alpha, Fading, etc

Dammit again, Adobe.
Where are the Convenience Functions?

As usual I will start out by bashing adobe for creating this pain in the ass. I don't know what happened at adobe labs but somewhere in the remake of Flash's text rendering engine for AS3 (which was an awesome improvement, no doubt), convenience functions were apparently forgotten completely and thus it takes like 15 lines of code to get 1 line of decent dynamic text going... and embedding fonts, well, that's just plain weird unless you're using the Flash IDE.

Oh well- here's a quick how-to for dynamically getting text on stage rotating with a nice font, in FlashDevelop.

.embedFonts = true or Text is Un-Fun and Ugly

Basically, to fade, rotate, or even just display nicely aliased text dynamically with the FlexSDK (I'm using Flash Develop + FlexSDK) you need to embed the font to compile with the SWF and assign it to a class name (see code comments below (this is my FlashDevelop / AS3 way of doing this) . Then, in your actionscript, you need to make sure that the textfield has the following pseudo-code equivalents:

  1. textfield's .embedFonts = true
  2. textfield's .antiAliasType = ADVANCED (see code below)
  3. your text format object needs to have .font set to the class name associated with your font.
  4. set textfield's text format object to format object with desired font after ANY change to the text in the textfield (will reset format on change of text string)

Other ways to load embedded fonts

There are other methods of going about this.  One worth noting that has worked well for me before, is to create a SWF for each font and load / use them as text containers dynamically, setting the text on the text box placed on stage with the Flash IDE ( i.e. loadedFontMC.textBox.text = "look aliased text!").  This is a somewhat sloppy way to get flash to embed a font, but it's a cool way to support LOTS of fonts externally without compiling them into and bloating the SWF.  This way, you don't have to preload them all just to run the app- plus using the Flash IDE is easy to choose the character sets from the  Flash properties menu and do more with the mouse than with code...

However, I find that for most purposes you only need 1 or 2 nice embedded fonts to cover all content and titles.  For that type of purpose, I prefer this dynamic style method as it is pure AS3 + actual font .ttf files, and has no other dependencies on external files.  Wrap this up in a nice class for yourself so you can just pass a font name as a parameter and don't have to deal with this again.  Maybe I'll post something like that soon... until then:

A Simple Demo Class Ready for FlashDevelop

You will, as usual, need the FlexSDK downloaded on your computer and attached to your project either by classpath, flexSDK settings in program settings, or by attaching .swc to your project library... take your pic.

Here's a full Main.as class that you can drop into a pure AS3 FlashDevelop project src/ directory and get your embedded font tested / working. Then, you can copy and paste the working code into your other projects.  Follow the instructions in the comments for adding the actual font's .ttf file to your lib/ directory (could be any directory really as long as the path is correct in your embed tag).

** Please note that this will embed the whole font into your compiled SWF (all crazy characters included).  To greatly reduce the size of the font added to the SWF, look into specifying the character set using the Embed tag and just embed the characters you need (like A-Z 0-1 and punctuation, not all the unnecessary German umlauts and whatnot).

"Embed Font and Rotate Test" 
Main.as Source:

package 
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.text.AntiAliasType;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.text.TextFormatAlign;
	import flash.utils.Timer;
	
	/**
	 * This is a simple font embedding test that rotates the text to show if embedding worked properly.  
	 * start by creating a new flash develop project and replacing the contents of the Main.as file with this entire source code
	 * 1) Right click the "lib" folder in the project tab and then pick a font from your fonts folder.  
	 * 2) Once the font file is added to the project view lib/ folder, right click the font and choose "Insert Into Document" to generate the basic Embed tag
	 * 3) add the fontFamily="FontClassName" to the embed tag properties and no semi colon at the end of the line so it will link to the next line
	 * 4) Add your class variable on the next line like... ((( public var FontClassName:Class; ))) with the same name as fontFamily
	 * 5) Use any textField.embedFonts and textFormat.font = FontClassName to set the font.
	 * 6) Rotation test below will demonstrate if it worked or not, non-embedded fonts will not rotate (will just disappear and not render until rotation is 0 again)
	 * @author One Giant Media
	 */
	public class Main extends Sprite 
	{	
		//[Embed(source = '../../..some_path_use_FD_AddToProject_RCmenu../FDproject/lib/FooFont.ttf', fontFamily="FooFont")]
		[Embed(source='../lib/GOTHIC.TTF', fontFamily="FooFont")]
		public var FooFont:Class;
		
		private var _textField:TextField;
		
		public function Main():void {
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			
			// create text
			_textField = createTestText("test some text here");
			
			// rotation test
			var rotateIt:Timer = new Timer(1 / 28);
			rotateIt.addEventListener(TimerEvent.TIMER, rotateText);
			rotateIt.start();
		}
		
		public function createTestText($text:String):TextField {
			var t:TextField = new TextField();
				t.antiAliasType = AntiAliasType.ADVANCED;
				t.embedFonts = true;
				t.autoSize = TextFieldAutoSize.LEFT;
				t.text = $text;
				t.x = stage.stageWidth / 2;
				t.y = stage.stageHeight / 2;
				
			var f:TextFormat = new TextFormat();
				f.font = "FooFont";
				f.align = TextFormatAlign.CENTER;
				f.color = 0x333333;
				f.size = 28;
				
			t.setTextFormat(f);
			
			return addChild(t) as TextField;
		}
		
		private function rotateText(e:TimerEvent = null):void {
			_textField.rotation++;
		}	
	}
}

24 comments (Add your own)

1. sean wrote:
what i really want to know now is if there is any way to set the background alpha of a text field. There is an .opaqueBackground property but nothing for alpha? You can set a stylesheet but CSS doesn't have anything for transparency, right? Ugh..

Wed, March 31, 2010 @ 4:44 AM

2. fakeartist wrote:
Very helpful. One correction though to make it work when compiling in flash player 10. Change this line.

[Embed(source='../lib/GOTHIC.TTF', fontFamily="FooFont", embedAsCFF="false")]

Without using embedAsCFF="false" nothing is seen, cause it's true by default.

One thing. You may want to delete the 3 above irrelevant comments.

Keep up.

Thu, July 22, 2010 @ 6:51 AM

3. sean wrote:
That is interesting, I do use/compile for FP10 and I've never had a problem without the embedAsCFF="false" setting. For me this test class works fine compiling with the latest Flex SDK for FP10.

I do see here in the adobe docs that apparently MX components will have issues if you don't explicitly set it. Glad you noted this, I could see this being a nightmare to debug a component without knowing that setting.

Thanks for the tip!

Thu, July 22, 2010 @ 5:21 PM

4. Jeremy Daley wrote:
@fakeartist: dude, you're the man

Thu, August 26, 2010 @ 12:32 PM

5. Mark wrote:
Thank you fakeartist!! I have searched countless websites and tried every combination and nothing was working until i added embedAsCFF="false"

Thu, September 9, 2010 @ 12:54 PM

6. Sean P wrote:
Here's some more information on this embedAsCFF content from bit 101.

http://www.bit-101.com/blog/?p=2555

Fri, September 10, 2010 @ 2:29 PM

7. Sean P wrote:
Here's some more information on this embedAsCFF content from bit 101.

http://www.bit-101.com/blog/?p=2555

Fri, September 10, 2010 @ 2:30 PM

8. Sean P wrote:
Here's some more information on this embedAsCFF content from bit 101...

http://www.bit-101.com/blog/?p=2555

Fri, September 10, 2010 @ 2:30 PM

9. Sean P wrote:
Here's some more information on this embedAsCFF content from bit 101...

http://www.bit-101.com/blog/?p=2555

Fri, September 10, 2010 @ 2:30 PM

10. SeanP wrote:
When compiling a SWF from flash CS5 that uses FlexSDK to instantiate a dynamic text field Century Gothic embedded in the font library with the character ranges selected, it works fine if Classic Text and a text field on stage with the font has "Use Device Fonts" selected. But, loading it as an external SWF into a FlashDevelop project also using FlexSDK (3.x) seems to mess it up, as no text appears.

Embedding the SAME font with the SAME weight in the FlashDevelop project seems to get the externally loaded SWF working again.... even thought the class name does not match. It seems in CS5 the Linkage/Class name is not important anymore, that it uses the Font Family name instead. Here's the embed tag that got the external SWF font displaying again:

[Embed(source='c:/windows/fonts/GOTHICB.TTF', fontFamily="Century Gothic", fontWeight="bold")]
public var CenturyGothic:Class;

Tue, October 5, 2010 @ 1:42 PM

11. SeanP wrote:
note: Using a different application domain also seems to correct this problem, but then my custom event classes don't seem to type cast correctly in the main applications event handlers... arrggghhh

Tue, October 5, 2010 @ 1:44 PM

12. Sean P wrote:
note: This post was originally about what is now called "Classic Text" in CS5 and above... With the new TLF text options you may need additional settings, like embedAsCFF and others. I will post more on TLF text in the future, but after having a lot of problems with getting it to look good, I'm sticking (for now) with Classic Text.

And Adobe, should anyone read this from your company, can you please make text EASIER instead of HARDER with each iteration? Seriously.

Tue, November 16, 2010 @ 12:33 PM

13. Riverstream wrote:
Many thanks fakeartist!
embedAsCFF="false" did the trick

Tue, December 7, 2010 @ 4:48 PM

14. neon wrote:
@fakeartist: THANK YOU!!!

Thu, January 6, 2011 @ 4:20 PM

15. Rafa wrote:
Thank you so much for your solution! You saved my weekend!!

Fri, February 18, 2011 @ 6:23 PM

16. Logos wrote:
Thank you fakeartist for tip for flash player 10!

Fri, April 22, 2011 @ 6:38 AM

17. Hyperblaster wrote:
fakeartist YOU ARE THE MAN!!!

Tue, May 17, 2011 @ 11:15 AM

18. Luxo wrote:
fakeartist!
YOU ARE MY IDOL!

Mon, June 27, 2011 @ 9:46 PM

19. Friedrich Haussmann wrote:
Thank you very much, fakeartist !

Tue, August 2, 2011 @ 1:05 PM

20. Jon Apgar wrote:
Thank you fakeartist,

embedAsCFF="false" saved the day! Spread the word!

Thu, September 8, 2011 @ 7:33 AM

21. bing wrote:
fakeartist = winner.

Wed, September 28, 2011 @ 10:57 PM

22. Joey wrote:
The font file still needs to be licensed if your embedding it, make sure you arent just using the End user fonts on your computer....IP infringmentsuit happend to me which they just forced me to pay the licensing fee plus lawyer costs :o(

Mon, November 14, 2011 @ 10:46 AM

23. joana wrote:
i'm so new to flash, can you give me a downloadable source code of this working. i don't know where to put this code. i cant seem to make it work.

Thu, January 12, 2012 @ 5:54 AM

24. Sean P wrote:
Joana,this tutorial is for FLASHDEVELOP software, not for Adobe Flash.

If you're in Flash and you're a beginner you should just use the text tool to put a text object on stage and animate it by hand.

If you are in Flash and you do want to create text from code, you want to change the line in the above source code that says "extends Sprite" to "extends MovieClip" and then you can use this as a Document class. You don't need anything on the timeline at that point, you can just run it with a blank stage and this creates text and rotates it. You will want to adjust the Embed font line to be a valid path on your computer to a font to test.


For more on Document Classes (an actionscript code file for the flash movie to run off of), see here:

http://active.tutsplus.com/tutorials/actionscript/quick-tip-how-to-use-a-document-class-in-flash/

http://www.youtube.com/watch?v=V01yZnRANLQ



good luck!

Thu, January 12, 2012 @ 1:09 PM

Add a New Comment

Enter the code you see below:
code
 

Comment Guidelines: No HTML is allowed. Off-topic or inappropriate comments will be edited or deleted. Thanks.