Switch embedding fonts at runtime in FLASH CS*/ AS3
In this post I’ll provide you just a quick way to change a TextField font family at runtime using ActionScript 3.0 and Flash Cs3/4 getting your embedded fonts from the Library .
Click on the displayed text below to see the switch font and test the final result:
To start, let’s create a new flash actionscript 3.0 file.
Open your library menu, click on New Font, select a font family from your hard disk and assign a Class Name (see image below)

Create a new class, Main.as, and associate it to Main.fla.
package { import flash.display.MovieClip; import flash.events.MouseEvent; import flash.text.TextField import flash.text.TextFieldAutoSize; import flash.text.TextFieldType; import flash.text.TextFormat; import flash.text.Font; public class Main extends MovieClip { private var displayedText:TextField private var futuraFont:Font; private var shirleyFont:Font; private var format:TextFormat public function Main() { // Create font istances (taken from Flash Library) futuraFont = new FuturaBK(); shirleyFont = new Shirl(); // Create the sample text init(); } /** * Displayed Text */ private function init():void { // Sample Text Creation displayedText = new TextField(); displayedText.autoSize = TextFieldAutoSize.LEFT; displayedText.type = TextFieldType.DYNAMIC; displayedText.selectable = false; displayedText.text = "Click me to switch the font Family" displayedText.addEventListener(MouseEvent.CLICK, setFontFamily) addChild(displayedText); // TextFormat // NOte: we don't set the font Family here format = new TextFormat(); format.color = 0xFF0000; format.size = 15; format.underline = true; // Set the Font Family ("Shirley" by default) setFontFamily(); } /** * set the the font family */ private function setFontFamily(e:MouseEvent=null):void { // Set / Update the .font property changing it after very click if (format.font == "Shirley") format.font = futuraFont.fontName; else format.font = shirleyFont.fontName; // Set Text Format (applyed on all the string minus last 10 letters) displayedText.setTextFormat(format, 0, displayedText.length-10); } } }
In few words, to apply a fontFamily to a textField we need to:
1) define a font istance
futuraFont = new FuturaBK();
2) create a TextFormat object
format = new TextFormat(); format.color = 0xFF0000; format.size = 15; format.underline = true;
3) initialize the TextFormat font property using the Font class fontName value
format.font = futuraFont.fontName;
4) set the new TextFormat (this line will set the font over all the string minus last 10 chars)
displayedText.setTextFormat(format, 0, displayedText.length-10);
or simply
displayedText.setTextFormat(format);
if you want set the new font to all the sentence











Leave your response!