AS Reference  :  Notes Index  :  Resources  :  About/Contact  :  Downloads

Creating text dynamically

On this page, we'll continue with the Oahu map application, adding the labels that accompany each control dynamically. The label is not part of the control (or it would pulsate along with the dot when moused over), so we'll use another MovieClip method, createTextField, to create a new textfield in a location we specify, and then fill it in with the text we saved previously in the placename property in the groupinfo array. We'll show how to format the text in two different ways: with css stylesheets and with Flash's TextFormat class.

To begin with, we need new fields in the groupinfo entries to describe the position of each textfield to be added to the stage. We can get that in the same way we did for the dot locations in the previous page, deleting all of the textfields from the stage when we're done. We don't need to create any movieclips with linkage ids, since we can just use the createTextField method to create a textfield rather than attaching a movieclip with a textfield in it. Here is the new groupinfo array:

var groupinfo:Array = [
   {placename:"Sunset Beach", myphoto:slider_mc.pic0, xloc:178, yloc:85,  xtext:146, ytext:64},
   {placename:"Kailua",       myphoto:slider_mc.pic1, xloc:347, yloc:245, xtext:352, ytext:230},
   {placename:"Hanauma Bay",  myphoto:slider_mc.pic2, xloc:367, yloc:318, xtext:355, ytext:324},
   {placename:"Waikiki",      myphoto:slider_mc.pic3, xloc:282, yloc:306, xtext:249, ytext:309},
   {placename:"Pearl Harbor", myphoto:slider_mc.pic4, xloc:217, yloc:273, xtext:189, ytext:294}
   ];  
  

Creating and styling dynamic text

With the information stored in groupinfo, we're ready to add the code to create the textfields, which will be done on program startup and so, in our our init routine. Here is the code to create a 200 x 20 pixel textfield named captioni (where i=0-4) at depth 100+i, and positioned at x=groupinfo[i].xtext, y=groupinfo[i].ytext:

function init() {	
   for (var i:Number=0; i < groupinfo.length; i++) {
      this.createTextField("caption"+i, 
                           100+i, 
                           groupinfo[i].xtext, 
                           groupinfo[i].ytext, 
                           200, 
                           20);
   }
}  
  

Formatting with css

If we leave it like that, the text will show up in whatever the default font is installed on the site visitor's machine. In order to format the text the way we want it, we can use css, first creating a new stylesheet in the variable declaration section of the program, and then applying it when the textfield is created. The stylesheet will contain a caption class that we'll apply to a paragraph in the textfield. The textfield must be html formatted (done with code below) for this to work:

var mapcss = new TextField.StyleSheet();
mapcss.setStyle(".caption", {
                              fontFamily:"Verdana", 
                              fontSize:"10px", 
                              color:"#000000"});
...
   
function init() {	
   for (var i:Number=0; i < groupinfo.length; i++) {
      this.createTextField("caption"+i, 
                           100+i, 
                           groupinfo[i].xtext, 
                           groupinfo[i].ytext, 
                           200, 
                           20);
      this["caption"+i].html = true;
      this["caption"+i].styleSheet = mapcss;
      this["caption"+i].selectable = false;
      this["caption"+i].text = "<p class='caption'>" + groupinfo[i].placename + "</p>";
    }
}

Ensure that site visitors will see the font you specify

That's all you have to do to make the sample work like the one above. If you want to ensure that the font you specify in the stylesheet is used even if the user doesn't have it installed, you need to embed the font, which is done in three steps:

  1. Turn the embedFont property on in the textfield (with code).
  2. Add the font to the library by right-clicking anywhere in a blank part of the library or choosing the dropdown menu in the upper right corner of the Library window and choosing New Font. Select the font you want from the dropdown list and give it a name. In the example below, I used a name of CaptionFont.



  3. Right-click the new font entry in the library and check the Export for Actionscript box.



Now our declaration and init function becomes (changes marked in bold):
var mapcss = new TextField.StyleSheet();
mapcss.setStyle(".caption", {fontFamily: "CaptionFont", 
                             fontSize: "10px", 
                             color:"#000000"});

function init() {	
   for (var i:Number=0; i < groupinfo.length; i++) {
      this.createTextField("caption"+i, 
                           100+i, 
                           groupinfo[i].xtext, 
                           groupinfo[i].ytext, 
                           200, 
                           20);
      this["caption"+i].html = true;
      this["caption"+i].embedFonts = true;
      this["caption"+i].styleSheet = mapcss;
      this["caption"+i].selectable = false;
      this["caption"+i].text = "<p class='caption'>" + groupinfo[i].placename + "</p>";
    }
}

The code for the above is included in oahumap_slider4.as, which you can download from the link at right. But that produces a font with somewhat fuzzy anti-aliased edges (which is ok unless you want it to match other non-anti-aliased fonts that may also be in the movie). If you're publishing to Flash 8, you can specify the aliasing on your text (in Flash 7, there's no way I know around the problem of fuzzy embedded dynamic text except to use a pixel font like the ones at Fonts For Flash.)

The TextFormat class with some new features in Flash 8

In Flash 6, 7 or 8, you can use a TextFormat class to format your text, instead of css. Additionally, in Flash 8, you can specify the line thickness and sharpness of the text, as shown in the image below (a screenshot of the output). In that example, different values of sharpness and thickness were applied, as you can see in the code below (complete source available in oahumap_slider4a.as):

// in the variable declaration section:
var mapfmt:TextFormat = new TextFormat();
mapfmt.font = "CaptionFont";
mapfmt.size = 9;

// in the init routine:
   for (var i:Number=0; i < groupinfo.length; i++) {
	  this.createTextField("caption"+i, 100+i, groupinfo[i].xtext, groupinfo[i].ytext, 200, 20);

      this["caption"+i].selectable = false;
      this["caption"+i].embedFonts = true;
      this["caption"+i].antiAliasType = "advanced";
	  
	  // some variations just so you can see
	  if (i==0) this["caption"+i].sharpness = -400;
	  else if (i==1) this["caption"+i].sharpness = 0;
	  else if (i==2) this["caption"+i].sharpness = 400;
  	  else if (i==3) this["caption"+i].thickness = -200;
  	  else if (i==4) this["caption"+i].thickness = 200;

      this["caption"+i].setNewTextFormat(mapfmt);	  
      this["caption"+i].text = groupinfo[i].placename;
   }

This is what those different values of sharpness and thickness produces (sharpness=0 appears to produce the best result; you can try experimenting with different combinations of sharpness and thickness to find the best for your application):

You can try your own combinations by downloading oahumap_slider4a.as and oahumap_slider4.fla from the link at right. Change the include line in the fla to point to oahumap_slider4a.as, and change the Publish Settings to publish to Flash 8.

Intro
Flash: What & How
Example Sites
Create
Draw, Edit Shapes
Gradients
More Drawing Tips
Import
A Sample
Animate
Frames, Keyframes
Motion Tweens
More Motion Tweens
Shape Tweens
Masks
Control
Stop/Replay
Movieclips Intro
Movieclip Reference
Site Structure 1
Slideshow Movieclip
Contact Form
Scroll Resume
Preloader
Site Structure 2
Publish
Display Options
Player Detection
Optimize
AS 2.0 Basics
Intro to Syntax
Playhead Commands
Playhead Cmds 2
Coded Tween
onEnterFrame
Intro to Classes
Declare/Assign
Comments, Trace
Simple Data Types
Arrays & Objects
Code Blocks
Operators
Beyond Buttons
Code Structure
Toggle Controls
Group of Buttons
Drag and Hit
Distort Magnifier
Scroll Text
Bee Game
Dart Shooter
Sound Control
Easing Slider
Easing Slider 2
Components Intro
Timers & Delays
Dynamic Content
Intro
Drawing API
Create Text
Attach Movieclips
Easing Slider 3
Easing Slider 4
Load jpg/swf
Sliding Viewer
Preload swf
XML
Easing Slider 5
Server Comm
LoadVars (w/ PHP)
AS - PHP Lookup
Text File
Database 1:LoadVars
Database 2:Remoting
Read from directory
AS 2.0 Classes
Intro
Math
Key
Date
Color
EventDispatcher
New Samples
Pie Chart
Event-model Emailer
Tween Sequence
Fuse Sequence
SVG in Flash
Bitmap Topo
SWF as Data Holder
Two-level Menu
Yahoo! Flash Maps
Class-based Game
ASTB Samples
Disclaimer
3D Outlines
Bounce Collide
Address Book
Save Drawings
Home  :  Notes Index  :  Resources  :  About/Contact  :  Downloads