What is Software? | What is Education? | What is Technology? | What is Research? | What is Wi-Fi? | What is Communication? | What is Customer Service?

Free SEO Tutorials & Help

Tutorials:   Adobe Flash   Adobe Photoshop   CorelDRAW   SEO  

Site Map

Website Development | Cable & Broadband Magazine | Solutions for Higher Education | Auction Anything Online

 

Adobe Flash Help & Tutorials

 Back to Topics

 

How to Work with Text and Strings in Flash

Working with Text and Strings

About text fields

Using the TextField class

Assigning text to a text field at runtime

About text field instance and variable names

Creating text fields at runtime

About manipulating text fields

Changing a text field's position

Changing a text field's dimensions at runtime

About loading text and variables into text fields

Using FlashVars to load and display text

Using LoadVars to load and display text

Loading variables by using LoadVars

Loading and displaying text from an XML document

Using fonts

Embedding characters

Embedding fonts

Creating custom character sets

Using TextField methods with embedded fonts

About sharing fonts

About font rendering and anti-alias text

Font rendering options in Flash

About continuous stroke modulation

Setting anti-alias with ActionScript

Setting tables for fonts

About text layout and formatting

About formatting anti-alias text

Using a grid fit type

Using the TextFormat class

Default properties of new text fields

Formatting text with Cascading Style Sheet styles

Supported CSS properties

Creating a style sheet object

Loading external CSS files

Creating new styles with ActionScript

Applying styles to a TextField object

Applying a style sheet to a TextArea component

Combining styles

Using style classes

Styling built-in HTML tags

An example of using styles with HTML

Using styles to define new tags

An example of using styles with XML

Using HTML-formatted text

Required properties and syntax for using HTML-formatted text

Anchor tag

Bold tag

Break tag

Font tag

Image tag

Italic tag

List item tag

Paragraph tag

Text format tag

Underline tag

About supported HTML entities

About embedding images, SWF files, and movie clips in text fields

Embedding SWF and image files

Embedding movie clip symbols

About specifying height and width values

Controlling embedded media with ActionScript

About making hypertext links out of embedded media

Example: Creating scrolling text

About strings and the String class

About the Strings panel

Using the Locale class

Using an input method editor

About the String class

Creating strings

About the escape character

Analyzing and comparing characters in strings

Converting and concatenating strings

Returning substrings

 
Working with Text and Strings

TOP

Many of the applications, presentations, and graphics that you create with Macromedia Flash Professional 8 or Macromedia Flash Basic 8 include some kind of text. You can use many different kinds of text. You might use static text in your layouts, but dynamic text for longer passages of text. Or you might use input text to capture user input, and text in an image for your background design. You can create text fields with the Flash authoring tool, or use ActionScript.

One way to display text is to use code to manipulate how strings appear before they are loaded and displayed on the Stage at runtime. You can work with strings in an application in several ways, such as sending them to a server and retrieving a response, parsing strings in an array, or validating strings that the user types into a text field.

This chapter describes several ways to use text and strings in your applications, focusing on using code to manipulate text.

The following list describes terminology used in this chapter.

Alias Aliased text does not use color variations to make its jagged edges appear smoother, unlike anti-aliased text (see following definition).

Anti-alias You use anti-aliasing to smooth text so the edges of characters that appear onscreen look less jagged. The Anti-Alias option in Flash makes text more legible by aligning text outlines along pixel boundaries, and is particularly effective for clearly rendering smaller font sizes.

Characters Characters are letters, numerals, and punctuation that you combine to make up strings.

Device fonts Device fonts are special fonts in Flash that are not embedded in a SWF file. Instead, Flash Player uses whatever font on the local computer that most closely resembles the device font. Because font outlines are not embedded, a SWF file size is smaller than using embedded font outlines. However, because device fonts are not embedded, the text that you create with these fonts looks different than expected on computer systems that do not have a font installed that corresponds to the device font. Flash includes three device fonts: _sans (similar to Helvetica and Arial), _serif (similar to Times Roman), and _typewriter (similar to Courier).

Fonts  Sets of characters with a similar font face, style, and size.

String  A sequence of characters.

Text  A series of one or more strings that can be displayed in a text field, or within a user interface component.

Text fields  A visual element on the Stage that lets you display text to a user. Similar to an input text field or text area form control in HTML, Flash lets you set text fields as editable (read-only), allow HTML formatting, enable multiline support, password masking, or apply a CSS stylesheet to your HTML formatted text.

Text formatting  You can apply formatting to a text field, or certain characters within a text field. Some examples of text formatting options that can be applied to text are: alignment, indenting, bold, color, font size, margin widths, italics, and letter spacing.

 

About text fields

TOP

A dynamic or input text field is a TextField object (an instance of the TextField class). When you create a text field in the authoring environment, you can assign it an instance name in the Property inspector. You can use the instance name in ActionScript statements to set, change, and format the text field and its content by using the TextField and TextFormat classes.

You can use the user interface to create several kinds of text fields, or you can use ActionScript to create text fields. You can create the following kinds of text fields in Flash:

Static text  Use static text to display characters that do not need to change, to display small amounts of text, or to display special fonts that are not available on most computers. You can also display uncommon fonts by embedding characters for dynamic text fields.

Dynamic text  Use dynamic text fields when you need to display characters that are updated or that change at runtime. Also, you can load text into dynamic text fields.

Input text Use input text fields when you need to capture user input. Users can type in these text fields.

Text components  You can use TextArea or TextInput components to display or capture text in your applications. The TextArea component is similar to a dynamic text field with built-in scroll bars. The TextInput component is similar to an input text field. Both components have additional functionality over their text field equivalents; however, they add more file size to your application.

NOTE : All text fields support Unicode. For information on Unicode, see About strings and the String class

The methods of the TextField class let you set, select, and manipulate text in a dynamic or input text field that you create during authoring or at runtime. For more information, see Using the

TextField class. For information on debugging text fields at runtime, see About displaying text field properties for debugging.

ActionScript also provides several ways to format your text at runtime. The TextFormat class lets you set character and paragraph formatting for TextField objects (see Using the TextFormat class). Flash Player also supports a subset of HTML tags that you can use to format text (see Using HTML-formatted text). Flash Player 7 and later supports the img HTML tag, which lets you embed not just external images but also external SWF files as well as movie clips that reside in the library (see Image tag).

In Flash Player 7 and later, you can apply Cascading Style Sheet (CSS) styles to text fields using the TextField.StyleSheet class. You can use CSS styles to style built-in HTML tags, define new formatting tags, or apply styles. For more information on using CSS, see Formatting text with Cascading Style Sheet styles.

You can also assign HTML formatted text, which might optionally use CSS styles, directly to a text field. In Flash Player 7 and later, HTML text that you assign to a text field can contain embedded media (movie clips, SWF files, and JPEG files). In Flash Player 8, you can also dynamically load PNG, GIF, and progressive JPEG images (Flash Player 7 does not support progressive JPEG images). The text wraps around the embedded media similar to how a web browser wraps text around media embedded in an HTML document. For more information, see Image tag.
 

Using the TextField class

TOP

The TextField class represents any dynamic or input (editable) text field you create using the Text tool in Flash. You use the methods and properties of this class to control text fields at runtime. TextField objects support the same properties as MovieClip objects, with the exception of the _currentframe, _droptarget, _framesloaded, and _totalframes properties. You can get and set properties and invoke methods for text fields dynamically.

To use ActionScript to control a dynamic or input text field, you must assign the text field an instance name in the Property inspector. You can then reference the text field with the instance name, and use the methods and properties of the TextField class to control the contents or basic appearance of the text field.

You can also create TextField objects at runtime, and assign them instance names, using the MovieClip.createTextField() method. For more information, see Creating text fields at runtime.

 

Assigning text to a text field at runtime

TOP

When you build applications with Flash, you may want to load text from an external source, such as a text file, an XML file, or even a remote web service. Flash provides a great deal of control over how you create and display text on the Stage, such as supporting text that is HTML formatted, plain text, XML formatted text, and external style sheets. Or you can use ActionScript to define a stylesheet.

To assign text to a text field, you can use the TextField.text or the TextField.htmlText property. Or, if you entered a value in the variable text field in the Property inspector, you can assign a value to the text field by creating a variable with the specified name. If you use version 2 of Macromedia Components Architecture in your Flash document, you can also assign values by creating bindings between components.

The following exercise assigns text to a text field at runtime.

To assign text to a text field at runtime:

  1. Using the Text tool, create a text field on the Stage.

  2. With the text field selected, in the Property inspector (Window > Properties > Properties), select Input Text from the Text Type pop-up menu, and enter headline_txt in the Instance Name text box.

    Instance names must consist only of letters, numbers, underscores (_), and dollar signs ($).

  3. Select Frame 1 of the Timeline, and open the Actions panel (Window > Actions).

  4. Type the following code in the Actions panel:

    headline_txt.text = "New articles available on Developer Center";

  5. Select Control > Test Movie to test the Flash document.

You can also create a text field with ActionScript, and then assign text to it. Type the following ActionScript on Frame 1 of the Timeline:

this.createTextField("headline_txt", this.getNextHighestDepth(), 100, 100, 300, 20);

headline_txt.text = "New articles available on Developer Center";

This code creates a new text field with the instance name headline_txt. The text field is created at the next highest depth, at the x and y coordinates of 100, 100, with a text field width of 200 pixels and a height of 20 pixels. When you test the SWF file (Control > Test Movie), the text "New articles available on Developer Center" appears on the Stage.

To create an HTML-formatted text field:

Use one of the following two steps to enable HTML formatting for the text field:

  • Select a text field and click Render Text as HTML in the Property inspector.

  • Set the text field's html property to true by using ActionScript (see the following code sample).

To apply HTML formatting to a text field by using ActionScript, type the following ActionScript on Frame 1 of the Timeline:

this.createTextField("headline_txt", this.getNextHighestDepth(), 100, 100, 300, 20);

headline_txt.html = true;

headline_txt.htmlText = "New articles available on <i>Developer Center</i>.";

The preceding code dynamically creates a new text field, enables HTML formatting, and displays the text "New articles available on Developer Center" on the Stage, with the word "Developer Center" appearing in italics.

CAUTION : When you use HTML formatted text with a text field (not components) on the Stage, you must assign the text to the text field's htmlText property instead of the text property.

 

About text field instance and variable names

TOP

In the Instance Name text box in the Property inspector, you must assign an instance name to a text field to invoke methods and get and set properties on that text field.

In the Var text box in the Property inspector, you can assign a variable name to a dynamic or input text field. You can then assign values to the variable. This is a deprecated functionality that you might use when you create applications for older versions of Flash Player (such as Flash Player 4). When you target newer players, target the text of a text field by using its instance name and ActionScript.

Do not confuse a text field's instance name with its variable name, however. A text field's variable name is a variable reference to the text contained by that text field; it is not a reference to an object.

For example, if you assigned a text field the variable name myTextVar, you can use the following code to set the contents of the text field:

var myTextVar:String = "This is what will appear in the text field";

However, you can't use the variable name myTextVar to set the text field's text property. You have to use the instance name, as shown in the following code:

// This won't work.

myTextVar.text = "A text field variable is not an object reference";

// For input text field with instance name "myField", this will work.

myField.text = "This sets the text property of the myField object";

Use the TextField.text property to control the contents of a text field, unless you're targeting a version of Flash Player that doesn't support the TextField class. This reduces the chances of a variable name conflict, which could result in unexpected behavior at runtime.

 

Creating text fields at runtime

TOP

You can use the createTextField() method of the MovieClip class to create an empty text field on the Stage at runtime. The new text field is attached to the timeline of the movie clip that calls the method.

To dynamically create a text field using ActionScript:

  1. Select File > New and then select Flash Document to create a new FLA file.

  2. Type the following ActionScript on Frame 1 of the Timeline:

    this.createTextField("test_txt", 10, 0, 0, 300, 100);

    This code creates a 300 x 100-pixel text field named test_txt with a location of (0, 0) and a depth (z-order) of 10.

  3. To access the methods and properties of the newly created text field, use the instance name specified in the first parameter of the createTextField() method.

    For example, the following code creates a new text field named test_txt, and modifies its properties to make it a multiline, word-wrapping text field that expands to fit inserted text. Then it assigns some text using the text field's text property:

    test_txt.multiline = true;

    test_txt.wordWrap = true;

    test_txt.autoSize = "left";

    test_txt.text = "Create new text fields with the MovieClip.createTextField() method.";

  4. Select Control > Test Movie to see the text field.

The text is created at runtime and appears on the Stage.

You can use the TextField.removeTextField() method to remove a text field created with createTextField(). The removeTextField() method does not work on a text field placed by the timeline during authoring.

NOTE : Some TextField properties, such as _rotation, are not available when you create text fields at runtime. You can rotate a text field only if it uses embedded fonts. See To embed a font symbol:.

 

About manipulating text fields

TOP

You can manipulate text fields that you create in a FLA file in several ways. You can manipulate a text field as long as you assign an instance name in the Property inspector, or you can assign one with code if you use code to create the field. The following simple example creates a text field, assigns text to it, and changes the border property of the field:

this.createTextField("pigeon_txt", this.getNextHighestDepth(), 100, 100, 200, 20);

pigeon_txt.text = "I like seeds";

pigeon_txt.border = true;

For a complete list of properties in the TextField class, see the ActionScript 2.0 Language Reference.

For examples of how to manipulate text fields, see the following sections:

  • Changing a text field's position

  • Changing a text field's dimensions at runtime

     

Changing a text field's position

TOP

You can change a text field's position on the Stage at runtime. You need to set new values for the text field's _x and _y properties, as shown in the following example.

To reposition a text field by using ActionScript:

  1. Create a new FLA file and save it as positionText.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    this.createTextField("my_txt", 10, 0, 0, 300, 200);

    my_txt.border = true;

    my_txt.text = "Hello world";

    my_txt._x = (Stage.width - my_txt._width) / 2;

    my_txt._y = (Stage.height - my_txt._height) / 2;

  3. Save the Flash document and select Control > Test Movie to see the text field centered on the Stage.

     

Changing a text field's dimensions at runtime

TOP

You may need to get or set a text field's dimensions dynamically at runtime, rather than in the authoring environment. The next example creates a text field on a timeline and sets its initial dimensions to 100 pixels wide by 21 pixels high. Later, the text field is resized to 300 pixels wide by 200 pixels high, and it is repositioned to the center of the Stage.

To resize a text field using ActionScript:

  1. Create a new Flash document and save it as resizeText.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    this.createTextField("my_txt", 10, 0, 0, 100, 21);

    my_txt.border = true;

    my_txt.multiline = true;

    my_txt.text = "Hello world";

    my_txt.wordWrap = true;

    my_txt._width = 300;

    my_txt._height = 200;

    my_txt._x = (Stage.width - my_txt._width) / 2;

    my_txt._y = (Stage.height - my_txt._height) / 2;

  3. Save the Flash document and select Control > Test Movie to see the results in the authoring environment.

The previous example resized a dynamically created text field to 300 pixels by 200 pixels at runtime, but when you load content from an external website and are not sure how much content will be returned, this technique may not be suitable for your needs. Fortunately, Flash includes a TextField.autoSize property, which you can use to automatically resize a text field to fit its contents. The following example demonstrates how you can use the TextField.autoSize property to resize the text field after text is added to the text field.

To automatically resize text fields based on content:

  1. Create a new Flash document and save it as resizeTextAuto.fla.

  2. Add the following code to Frame 1 of the main Timeline:

    this.createTextField("my_txt", 10, 10, 10, 160, 120);

    my_txt.autoSize = "left";

    my_txt.border = true;

    my_txt.multiline = true;

    my_txt.text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

    my_txt.wordWrap = true;

    NOTE : If you paste this code directly into the Actions panel from some versions of Flash Help, you may encounter line breaks in the long text string. In this case, the code won't compile. If you encounter this situation, enable Hidden Characters on the pop-up menu of the Actions panel, and then remove the line break characters in the long text string.

  3. Save the Flash document and select Control > Test Movie to view the Flash document in the authoring environment.

Flash resizes the text field vertically so that all the content can be displayed without being cropped by the text field boundaries. If you set the my_txt.wordWrap property to false, the text field resizes horizontally to accommodate the text.

To enforce a maximum height on the auto-sized text field (so that the text field height doesn't exceed the boundaries of the Stage), use the following code.

if (my_txt._height > 160) {

my_txt.autoSize = "none";

my_txt._height = 160;

}

You must add some scrolling functionality, such as a scroll bar, to allow users to view the remainder of the text. Alternatively, you can roll the mouse pointer over the text; this method is often adequate while testing this code.

 

About loading text and variables into text fields 

TOP

You can load text into a Flash document several ways, including (but certainly not limited to) using FlashVars, LoadVars, XML, or web services. Perhaps the simplest method of passing text into a Flash document is to use the FlashVars property, which passes short strings of text into a Flash document through the object and embed tags in the HTML code that you use to embed the SWF file in an HTML page. Another easy way to load text or variables into a Flash document is to use the LoadVars class, which can load large blocks of text or load a series of URL encoded variables from a text file.

As you can see from the previous examples in this section, some ways of loading text into a SWF file are easier than others. However, if you syndicate data from external sites, you might not have a choice for the format of the data that you need to load.

Each way of loading and/or sending data to and from a SWF file has its pros and cons. XML, web services, and Flash Remoting are the most versatile for loading external data, but they are also the most difficult to learn. For information on Flash Remoting, see www.macromedia.com/support/flashremoting.

FlashVars and LoadVars are much simpler, as demonstrated in Using FlashVars to load and display text and Using LoadVars to load and display text, but they can be much more limited in the types and formats of data that you can load. Also, you must follow security restrictions when you send and load data. For information on security, see Understanding Security. For more information on loading external data, see Working with External Data.

The following sections show you different ways to load text and variables into your documents:

  • Using FlashVars to load and display text

  • Using LoadVars to load and display text

  • Loading variables by using LoadVars

  • Loading and displaying text from an XML document

Using FlashVars to load and display text

TOP

Using FlashVars is simple, but requires you to publish your SWF files along with HTML documents. You modify the generated HTML code and include the FlashVars properties in both the object and embed tags. You can then test the Flash document by viewing the modified HTML document in your web browser.

To use FlashVars to pass variables from HTML to your Flash document:

  1. Create a new Flash document and save it as flashvars.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    this.createTextField("my_txt", 10, 10, 10, 100, 21);

    my_txt.text = _level0.username;

  3. Save the Flash document and select File > Publish to generate the HTML and SWF files.

    NOTE : An HTML document publishes, by default, to the same directory as your FLA file. If an HTML document does not publish, select File > Publish Settings and then select the Formats tab.

  4. Make sure that you select HTML.

  5. Open up the flashvars.html document in a text or HTML editor.

    In the HTML document, modify the code inside the object tag to match the following.

    The code you need to add is in boldface.

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="550" height="400" id="flashvars" align="middle">

    <param name="allowScriptAccess" value="sameDomain" />

    <param name="movie" value="flashvars.swf" />

    <param name="FlashVars" value="username=Thomas" />

    <param name="quality" value="high" />

    <param name="bgcolor" value="#ffffff" />

    <embed src="flashvars.swf" FlashVars="username=Thomas" quality="high" bgcolor="#ffffff" width="550" height="400" name="flashvars" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />

    </object>

  6. Save your changes to the HTML document.

  7. Open the modified HTML in a web browser.

The SWF file displays the name "Thomas" in the dynamically created text field on the Stage.

 

Using LoadVars to load and display text

TOP

You can also use the LoadVars class to load content into a SWF file, which loads text or variables from an external file on the same server, or even content from a different server. The next example demonstrates how to dynamically create a text field and populate it with the contents of a remote text file.

To use LoadVars to populate a text field with external text:

  1. Create a new Flash document and save it as loadvarsText.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    this.createTextField("my_txt", 10, 10, 10, 320, 100);

    my_txt.autoSize = "left";

    my_txt.border = true;

    my_txt.multiline = true;

    my_txt.wordWrap = true;

    var lorem_lv:LoadVars = new LoadVars();

    lorem_lv.onData = function (src:String):Void {

    if (src != undefined) {

    my_txt.text = src;

    } else {

    my_txt.text = "Unable to load external file.";

    }

    }

    lorem_lv.load("http://www.helpexamples.com/flash/lorem.txt");

    The first block of code in the previous snippet creates a new text field on the Stage and enables multiline and word wrapping. The second block of code defines a new LoadVars object that is used to load a text file (lorem.txt) from a remote web server and display its contents into the my_txt text field created earlier.

  3. Save the Flash document and select Control > Test Movie to test the SWF file.

After a slight delay, Flash displays the contents of the remote file in the text field on the Stage.

 

Loading variables by using LoadVars

TOP

The LoadVars class also lets you load variables in a URL-encoded format, similar to passing variables in the query string in a web browser. The following example demonstrates how to load a remote text file into a SWF file and display its variables, monthNames and dayNames.

To load variables from a text file by using LoadVars:

  1. Create a new Flash document and save it as loadvarsVariables.fla.

  2. Add the following code to Frame 1 of the Timeline:

    this.createTextField("my_txt", 10, 10, 10, 320, 100);

    my_txt.autoSize = "left";

    my_txt.border = true;

    my_txt.multiline = true;

    my_txt.wordWrap = true;

    var lorem_lv:LoadVars = new LoadVars();

    lorem_lv.onLoad = function (success:Boolean):Void {

    if (success) {

    my_txt.text = "dayNames: " + lorem_lv.dayNames + "\n\n";

    my_txt.text += "monthNames: " + lorem_lv.monthNames;

    } else {

    my_txt.text = "Unable to load external file.";

    }

    }

    /* contents of params.txt:

    &monthNames=January,February,...&dayNames=Sunday,Monday,...

    */

    lorem_lv.load("http://www.helpexamples.com/flash/params.txt");

  3. Save the Flash document and select Control > Test Movie from the main menu.

Because you are using the LoadVars.onLoad() method instead of LoadVars.onData(), Flash parses out the variables and creates variables within the LoadVars object instance. The external text file contains two variables, monthNames and dayNames, which both contain strings.

 

Loading and displaying text from an XML document

TOP

XML data is a popular way to distribute content on the Internet, in part because it is a widely accepted standard for organizing and parsing data. As such, XML is an excellent choice for sending and receiving data from Flash; however, XML is slightly more difficult to learn than using LoadVars and FlashVars to load data and display text.

To load text into Flash from an external XML document:

  1. Create a new Flash document and save it as xmlReviews.fla.

  2. Add the following code to Frame 1 of the Timeline:

    this.createTextField("my_txt", 10, 10, 10, 320, 100);

    my_txt.autoSize = "left";

    my_txt.border = true;

    my_txt.multiline = true;

    my_txt.wordWrap = true;

    var reviews_xml:XML = new XML();

    reviews_xml.ignoreWhite = true;

    reviews_xml.onLoad = function (success:Boolean):Void {

    if (success) {

    var childItems:Array = reviews_xml.firstChild.childNodes;

    for (var i:Number = 0; i < childItems.length; i++) {

    my_txt.text += childItems[i].firstChild.firstChild.nodeValue + "\n";

    }

    } else {

    my_txt.text = "Unable to load external file.";

    }

    }

    reviews_xml.load("http://www.helpexamples.com/flash/xml/reviews.xml");

    The first block of code in the preceding snippet creates a new text field on the Stage. This text field is used to display various parts of the XML document that is loaded later. The second block of code handles creating an XML object that will be used to load the XML content. Once the date is completely loaded and parsed by Flash, the XML.onLoad() event handler is invoked and displays the contents of the XML packet in the text field.

  3. Save the Flash document and select Control > Test Movie to test the SWF file.

Flash displays the following output in the text field on the Stage:

Item 1

Item 2

...

Item 8

 

Using fonts

TOP

Fonts are sets of characters with a similar font face, style, and size. No matter what you create using Flash Basic 8 or Flash Professional 8, you will probably use text with at least one or two fonts in your Flash applications. If you build animations, and you are not sure if your end users will have a specific font installed on their systems, you need to understand the basics about embedding fonts.

The following sections show you how to embed characters, entire fonts, shared fonts, and other techniques for working with fonts in Flash 8.

The following example shows you how to add and remove embedded characters and character sets in a Flash document.

To add and remove embedded characters and character sets:

  1. Create a new Flash document and save it as embedding.fla.

  2. Create a dynamic text field on the Stage by using the Text tool.

  3. Click Embed to launch the Character Embedding dialog box.

  4. Select a specific character set to embed by clicking it with your mouse pointer.

    To select multiple character sets, you can use the Shift or Control key while selecting items with your mouse pointer. To select a block of character sets, select a character set with your mouse pointer, press and hold Shift, and click a new character set. Using Shift selects every character set between the two selected character sets. To select multiple non-sequential character sets, press and hold the Control key while you select character sets. You can also quickly select multiple character sets by selecting a character set with your mouse, and with the mouse button still held down, drag your mouse over multiple character sets.

  5. To remove a specific character set that you added earlier, press and hold the Control key and deselect the character set by clicking it with your mouse pointer.

  6. To remove every selected character set and any specified characters in the Include these characters text input field, click Don't Embed.

Don't Embed clears any previously specified individual characters or character sets.

CAUTION : Clicking Don't Embed in the Character Embedding dialog box removes any specified embedded characters and character sets that were previously chosen without asking you to confirm.

 

Embedding characters

TOP

If you're working with embedded fonts and know exactly what characters you need, you can reduce file size by embedding only the characters that you need instead of including additional, unused font outlines. To embed certain characters within a text field and not embed a whole character set, use the Character Embedding dialog box to specify which specific characters you want to embed.

To embed specific characters for use in a text field:

  1. Create a new Flash document and save it as charembed.fla.

  2. Using the Text tool, create a text field on the Stage and set the text field's text type to either dynamic or input.

  3. With the text field still selected on the Stage, click Embed in the Property inspector to open the Character Embedding dialog box.

    The Character Embedding dialog box lets you set which character sets will embed in the Flash document (as well as how many glyphs per character set), specify specific characters to embed, and tells you the total number of glyphs being embedded for this text field.

  4. Type the string hello world into the Include these characters text box.

    The dialog box tells you that a total of 8 glyphs will be embedded for this text field. Even though the string "hello world" contains 11 characters, Flash only embeds unique glyphs, so the letters l and o are embedded once instead of multiple times.

  5. Click OK to apply the changes and return to your document.

  6. Using the Text tool, create a new text field on the Stage.

  7. Set the text field's text type to dynamic in the Property inspector.

  8. Type the string hello world into the text field on the Stage.

  9. Click Embed in the Property inspector to open the Character Embedding dialog box again.

  10. Click Auto Fill to automatically populate the Include These Characters text box.

You will see the string "helo wrd". Instead of having to tell Flash which characters you want to include, Flash can determine all unique characters in the specified text field for you.

TIP : Flash can determine characters to embed automatically only if the text field contains text on the Stage. If the text field is populated by using ActionScript, you must specify which characters you want to embed for the text field.

 

Embedding fonts

TOP

When you embed fonts, Flash stores all of the font information in the SWF file so the font is displayed properly even if it's not installed on the user's computer. If you use a font in your FLA file that isn't installed on a user's system, and you don't embed the font in the SWF file, Flash Player automatically selects a substitute font to use instead.

NOTE : You need to embed a font only if you're using dynamic or input text fields. If you use a static text field, you don't need to embed the font.

To embed a font symbol:

  1. Select Window > Library to open the current FLA file's library.

    Open the library that you want to add the font symbol to.

  2. Select New Font from the library's pop-up menu (upper-right corner of the Library panel).

  3. Type a name for the font symbol in the Name text box of the Font Symbol Properties dialog box.

  4. Select a font from the Font menu or type the name of a font in the Font text box.

  5. Select Bold, Italic, or Alias text if you want to apply a style to the font.

  6. Enter the font size to embed, and then click OK to apply the changes and return to your document.

Your font now appears in the current document's library.

After you've embedded a font in your library, you can use it with a text field on the Stage.

To use an embedded font symbol in your Flash document:

  1. Follow the steps in the procedure under Embedding fonts to embed a font in your library.

  2. Use the Text tool to create a text field on the Stage.

  3. Type some text in the text field.

  4. Select the text field, and open the Property inspector.

    1. Set the text field to single-line.

    2. Select the name of the embedded font by using the Font drop-down menu.

    Embedded fonts have an asterisk (*) after the font name.

  5. Click Embed in the Property inspector to launch the Character Embedding dialog box.

    The Character Embedding dialog box lets you select the individual characters or character sets that you want to embed for the selected text field. To specify what characters to embed, either type the characters into the text box in the dialog box, or click Auto Fill to automatically populate the text field with the unique characters currently in the text field. If you aren't sure which characters you will need (for example, because your text loads from an external file or a web service), you can select entire sets of characters to embed, such as Uppercase [A..Z], Lowercase [a..z], Numerals [0..9], Punctuation [!@#%...], and character sets for several different languages.

    NOTE : Each character set you select increases the final size of the SWF file because Flash has to store all of the font information for each character set that you use.

  6. Select the individual characters or character sets you want to embed, and then click OK to apply the changes and return to your document.

  7. Select Control > Test Movie to test the Flash document in the authoring environment.

    The embedded font is displayed in the text field on the Stage. To properly test that the font is embedded, you might need to test on a separate computer without the embedded font installed.

    Or you can set the TextField._alpha or TextField._rotation properties for the text field with embedded fonts, because these properties work only on embedded fonts (see the following steps).

  8. Close the SWF file and return to the authoring tool.

  9. Select the text field on the Stage, and open the Property inspector.

    1. Set the text field's Text type to Dynamic Text.

    2. Type font_txt into the Instance Name text box.

  10. Add the following code to Frame 1 of the Timeline:

    font_txt._rotation = 45;

  11. Select Control > Test Movie again to view the changes in the authoring environment.

The embedded font rotates 45 clockwise, and you can still see the text because it's embedded in the SWF file.

CAUTION : If you don't embed a font within your Flash document and Flash Player automatically chooses a font substitute on the user's computer, the TextField.font property returns the original font used within the FLA, not the name of the substituted font.

NOTE : If you use embedded fonts with a variety of styles in your text fields, you must embed the style that you want to use. For example, if you're using an embedded font called Times, and then want a word to be italic, you must make sure to embed both the normal and italic character outlines. Otherwise, the text won't appear in the text field.

 

Creating custom character sets

TOP

In addition to using the Flash default character sets, you can also create your own character sets and add them to the Character Embedding dialog box. For example, you might need to allow some fields to include Extended Latin, to support various accented characters. However, perhaps you don't need the numerals and punctuation, or perhaps you only need uppercase characters. Rather than embedding entire character sets, you can create a custom character set that contains only the characters that you need. This way you can keep the size of your SWF file as small as possible, because you don't store any extra font information for the characters that you don't need.

To create a custom character set, you must edit the UnicodeTable.xml file, located in the C:\Program Files\Macromedia\Flash 8\<language>\First Run\FontEmbedding\ directory. This file defines the default character sets and the character ranges and characters that they contain.

Before you create a custom character set, you should understand the necessary XML structure. The following XML nodes define the Uppercase [A..Z] character set:

<glyphRange name="Uppercase [A..Z] " id="1" >

<range min="0x0020" max ="0x0020" />

<range min="0x0041" max ="0x005A" />

</glyphRange>

Notice that the glyphRange node includes name, Uppercase [A..Z], and id. A glyphRange node can have as many range child nodes as you need. A range can be a single character, such as 0x0020 (the space character), seen in the previous snippet, or a range of characters, such as the second range child node. To embed only a single character, set the min value and the max value to the same unicode character value.

Another example of an XML glyphRange node is the Numerals [0..9] node:

<glyphRange name="Numerals [0..9] " id="3" >

<range min="0x0030" max ="0x0039" />

<range min="0x002E" max ="0x002E" />

</glyphRange>

This range of characters includes the Unicode values 0x0030 (zero) through 0x0039 (9), as well as 0x002E (.).

Before you create a custom character set, you need to know the characters and their corresponding Unicode values. The best place to find Unicode values is the Unicode Standards web site, www.unicode.org, which contains the Unicode Character Code chart for dozens of languages.

CAUTION : To add custom character sets, you need to edit an XML file in the Flash installation folder. Before you edit this file, you should make a backup copy in case you want to revert to the original Unicode table.

CAUTION : Macromedia recommends that you do not modify the existing character sets that are installed with Flash, and that you instead make your own custom character sets that include the characters and punctuation that you require.

To create and use a custom character set:

  1. Open the UnicodeTable.xml document, located in the <Flash install directory>\<language>\First Run\FontEmbedding\ directory, using an XML or text editor such as Notepad or TextEdit.

    NOTE : Remember to save a backup of this document, in case you want to revert to the original file that is installed with Flash.

  2. Scroll to the bottom of the XML document and add the following XML code directly before the closing </fontEmbeddingTable> node:

    <glyphRange name="Uppercase and Numerals [A..Z,0..9] " id="100" >

    <range min="0x0020" max ="0x0020" />

    <range min="0x002E" max ="0x002E" />

    <range min="0x0030" max ="0x0039" />

    <range min="0x0041" max ="0x005A" />

    </glyphRange>

  3. Save your changes to UnicodeTable.xml.

    If you have Flash open, you must restart the application before you can use the new character set.

  4. Open or restart Flash and then create a new Flash document.

  5. Add a new TextField instance on the Stage by using the Text tool.

  6. Set the Text type of the TextField to Dynamic in the Property inspector, and then click Embed Character Options to open the Character Embedding dialog box.

  7. Scroll to the bottom of the Character Embedding dialog box and select your new custom character set, Uppercase and Numerals [A..Z,0..9] (38 glyphs).

  8. Select any other character sets and click OK.

If you select your custom character set, Uppercase and Numerals [A..Z,0..9], as well as the default Uppercase [A..Z] or Numerals [0..9] character set, notice that the number of glyphs that are embedded doesn't change. This is because all of the uppercase characters are included in your custom character set, and Flash doesn't include duplicate characters, which keeps the file size as small as possible. If you select the Punctuation character set, which includes 52 glyphs, as well as your custom character set, which includes 38 glyphs, Flash stores information for only 88 glyphs instead of 90. This happens because two overlapping characters, the space and the period, are already included in your custom character set.

TIP : The position of a character set in the Character Embedding dialog box is determined by its location in the XML document. You can reorder the character sets, including your custom character sets, by moving <glyphRange> packets in the XML file.

 

Using TextField methods with embedded fonts

TOP

Methods of the TextField class provide useful functionality for your applications. For example, you can control the thickness of a text field by using ActionScript as demonstrated in the following example.

To set a text field's thickness using ActionScript:

  1. Create a new Flash document and save it as textfieldThickness.fla.

  2. Open the Library panel, and select New Font from the pop-up menu (in the upper-right corner of the Library panel).

    The Font Symbol Properties dialog box opens. This dialog box lets you select a font to embed in the SWF file (including a font style and font size). You can also assign a font name that appears in the document's library and the font drop-down menu in the Property inspector (if you have a text field selected on the Stage).

    Select the Times New Roman font from the Font drop-down menu.

    Make sure that you deselect the Bold and Italic options.

    Set the size to 30 pixels.

    Enter a font name of Times (embedded)

    Click OK.

  3. In the library, right-click the font symbol, and then select Linkage from the context menu.

    Flash opens the Linkage Properties dialog box.

  4. Select the Export for ActionScript and Export in first frame options and click OK.

  5. Add the following ActionScript to Frame 1 of the Timeline:

    // 1

    this.createTextField("thickness_txt", 10, 0, 0, Stage.width, 22);

    this.createTextField("lorem_txt", 20, 0, 20, Stage.width, 0);

    lorem_txt.autoSize = "left";

    lorem_txt.embedFonts = true;

    lorem_txt.antiAliasType = "advanced";

    lorem_txt.text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

    lorem_txt.wordWrap = true;

    // 2

    var style_fmt:TextFormat = new TextFormat();

    style_fmt.font = "Times (embedded)";

    style_fmt.size = 30;

    lorem_txt.setTextFormat(style_fmt);

    // 3

    var mouseListener:Object = new Object();

    mouseListener.onMouseMove = function():Void {

    // Values for TextField.thickness can range from -200 to +200.

    lorem_txt.thickness = Math.round(_xmouse * (400 / Stage.width) - 200);

    thickness_txt.text = "TextField.thickness = " + lorem_txt.thickness;

    };

    Mouse.addListener(mouseListener);

    The first block of code creates two text fields, thickness_txt and lorem_txt, and positions them on the Stage. The lorem_txt text field sets its embedFonts property to true and populates the text field with a block of text.

    The second block of code defines a text format with the font face Times New Roman, sets the font size to 30 pixels, and applies the text format to the lorem_txt text field.

    The third, and final, block of code defines and assigns a mouse listener for the onMouseMove event. When the mouse pointer moves horizontally across the Stage, the TextField.thickness property changes between -200 and +200, depending on the current value of _xmouse.

  6. Save your changes to the FLA file.

  7. Select Control > Test Movie to test your Flash document.

When you move the mouse pointer to the left half of the Stage, the font thickness decreases. When you move the mouse pointer to the right half of the Stage, the font thickness increases.

 

About sharing fonts

TOP

To use a font as a shared library item, you can create a font symbol in the Library panel, and then assign the following attributes to the font symbol:

  • An identifier string

  • A URL where the document containing the font symbol will be posted

In this way, you can link to the font and use it in a Flash application without the font being stored in the FLA file.

 

About font rendering and anti-alias text

TOP

Font rendering in Flash controls the way that your text appears in a SWF file; that is, how it is rendered (or drawn) at runtime. The advanced font rendering technology used in Flash Player 8, called FlashType. FlashType uses advanced rendering technology to help make text appear legible and clear at small to regular font sizes, such as when you apply advanced anti-aliasing toyour text fields. This technology is discussed in more detail later in this section.

Anti-aliasing lets you smooth text so that the edges of characters displayed onscreen look less jagged, which can be particularly helpful when you want to display text using small text sizes.

The Anti-Alias option for text makes characters more legible by aligning text outlines along pixel boundaries, and is particularly effective for more clearly rendering small font sizes.You can apply anti-aliasing for each text field in your application, rather than for individual characters.

Anti-aliasing is supported for static, dynamic, and input text if the user has Flash Player 7 or later. It is supported only for static text if the user has an earlier version of Flash Player.

Advanced anti-aliasing options are available for Flash Player 8.

Flash Basic 8 and Flash Professional 8 include a significantly improved font rasterization and rendering technology, called FlashType, for working with anti-aliased fonts. Flash 8 includes five font rendering methods, which are available only when you publish SWF files for Flash Player 8. If you are publishing files for use with Flash Player 7 or earlier versions, only the Anti-Alias for

Animation option is available for use with your text fields.

FlashType is a high-quality font rendering technology that you can enable by using either the Flash 8 authoring tool or ActionScript. The FlashType technology lets you render font faces with high-quality output at small sizes, with more control. You can apply FlashType to embedded font rendering for static, dynamic, and input text fields. The improved capabilities mean that embedded text appears at the same level of quality as device text, and fonts appear the same on different platforms.

The font rendering methods available for Flash Player 8 are Device Fonts, Bitmap Text (no anti-alias), Anti-Alias for Animation, Anti-Alias for Readability, and Custom Anti-Alias, which lets you define a custom value for thickness and sharpness. For more information on these options, see Font rendering options in Flash.

NOTE : When you open existing FLA files in Flash 8, your text is not automatically updated to the Anti-Alias for Readability option; you must select individual text fields and manually change the anti-aliasing settings to take advantage of the FlashType rendering technology.

Advanced and custom anti-alias features support the following:

  • Scaled and rotated text

  • All fonts (plain, bold, or italic) up to 255 pt size

  • File exporting to most formats (such as JPEG or GIF files)

Advanced and custom anti-alias features do not support the following:

  • Flash Player 7 or earlier

  • Skewed or flipped text

  • Printing

  • File exporting to the PNG file format

NOTE : When text is animated, the player turns off advanced anti-alias to improve the appearance of your text while it's moving. After the animation is complete, anti-alias is turned back on.

A sample file on your hard disk shows how to apply and manipulate anti-aliased text in an application. You use the FlashType rendering technology to create small text that's highly legible.

This sample also demonstrates how text fields can scroll quickly and smoothly when you use the cacheAsBitmap property.

 

Font rendering options in Flash

TOP

Five different font rendering options are available in Flash 8. To select an option, select the text field and open the Property inspector. Select an option from the Font rendering method pop-up menu.

Device Fonts  Produces a smaller SWF file size. The option renders using fonts that are currently installed on the end user's computer.

Bitmap Text (no anti-alias) Produces sharp text edges, without anti-aliasing. This option produces a larger SWF file size, because font outlines are included in the SWF file.

Anti-Alias for Animation Produces anti-alias text that animates smoothly. The text also animates faster in some situations, because alignment and anti-alias are not applied while the text animates. You do not see a performance improvement when you use big fonts with lots of letters, or scaled fonts. This option produces a larger SWF file size, because font outlines are included in the SWF file.

Anti-Alias for Readability The advanced anti-aliasing engine is used for this option. This option offers the highest-quality text, with the most legible text. This option produces the largest SWF file size, because it includes font outlines, and also special anti-aliasing information.

Custom Anti-Alias The same as Anti-Alias for Readability, but you can visually manipulate the anti-aliasing parameters to produce a specific appearance. This option is useful to produce the best possible appearance for new or uncommon fonts.

 

About continuous stroke modulation

TOP

The FlashType font rendering technology exploits the inherent properties of distance fields to provide continuos stroke modulation (CSM); for example, continuous modulation of both the stroke weight and the edge sharpness of the text. CSM uses two rendering parameters to control the mapping of adaptively sampled distance field (ADF) distances to glyph density values.

Optimal values for these parameters are highly subjective; they can depend on user preferences, lighting conditions, display properties, typeface, foreground and background colors, and point size. The function that maps ADF distances to density values has an outside cutoff, below which values are set to 0, and an inside cutoff, above which values are set to a maximum density value, such as 255.

 

Setting anti-alias with ActionScript

TOP

Flash 8 offers two types of anti-aliasing: normal and advanced. Advanced anti-aliasing is available only in Flash Player 8 and later, and can be used only if you embed the font in the library and have the text field's embedFonts property set to true. For Flash Player 8, the default setting for text fields created using ActionScript is normal.

To set values for the TextField.antiAliasType property, use the following string values:

normal Applies the regular text anti-aliasing. This matches the type of anti-aliasing that Flash Player used in version 7 and earlier.

advanced Applies advanced anti-aliasing for improved text readability, which is available in Flash Player 8. Advanced anti-aliasing allows font faces to be rendered at very high quality at small sizes. It is best used with applications that have a lot of small text.

TIP : Macromedia does not recommend advanced anti-aliasing for fonts larger than 48 points.

To use ActionScript to set anti-alias text, see the following example.

To use advanced anti-aliasing:

  1. Create a new Flash document and save it as antialiastype.fla.

  2. Create two movie clips on the Stage and give them instances names of normal_mc and advanced_mc.

    You will use these movie clips to toggle between the two types of anti-aliasing: normal and advanced.

  3. Open the Library panel and select New Font from the pop-up menu in the upper-right corner of the Library panel.

    The Font Symbol Properties dialog box opens, in which you can select a font to embed in the SWF file (including a font style and font size). You can also assign a font name that appears in the document's library and in the Font drop-down menu in the Property inspector (if you have a text field selected on the Stage).

    • Select the Arial font from the Font drop-down menu.

    • Make sure that the Bold and Italic options are not selected.

    • Set the size to 10 pixels.

    • Enter the font name of Arial-10 (embedded).

    • Click OK.

  4. In the library, right-click the font symbol and select Linkage from the context menu.

    The Linkage Properties dialog box appears.

  5. Select the Export for ActionScript and Export in First Frame options, enter the linkage identifier Arial-10, and click OK.

  6. Add the following ActionScript to Frame 1 of the main Timeline:

    var text_fmt:TextFormat = new TextFormat();

    text_fmt.font = "Arial-10";

    text_fmt.size = 10;

    this.createTextField("my_txt", 10, 20, 20, 320, 240);

    my_txt.autoSize = "left";

    my_txt.embedFonts = true;

    my_txt.selectable = false;

    my_txt.setNewTextFormat(text_fmt);

    my_txt.multiline = true;

    my_txt.wordWrap = true;

    var lorem_lv:LoadVars = new LoadVars();

    lorem_lv.onData = function(src:String) {

    if (src != undefined) {

    my_txt.text = src;

    } else {

    my_txt.text = "unable to load text file.";

    }

    };

    lorem_lv.load("http://www.helpexamples.com/flash/lorem.txt");

    normal_mc.onRelease = function() {

    my_txt.antiAliasType = "normal";

    };

    advanced_mc.onRelease = function() {

    my_txt.antiAliasType = "advanced";

    };

    The preceding code is separated into four key areas. The first block of code creates a new TextFormat object, which specifies a font and font size to be used for a text field that will be created shortly. The specified font, Arial-10, is the linkage identifier for the font symbol that you embedded in a previous step.

    The second block of code creates a new text field with the instance name my_txt. In order for the font to be properly embedded, you must set embedFonts to true for the text field instance.

    The code also sets the text formatting for the new text field to the TextFormat object that you created earlier.

    The third block of code defines a LoadVars instance that populates the text field on the Stage with the contents of an external text file. After the document is fully loaded (but not parsed), the entire contents of the file are copied into the my_txt.text property, so that they are displayed on the Stage.

    The fourth, and final, block of code defines onRelease event handlers for both the normal_mc movie clip and the advanced_mc movie clip. When the user clicks and releases either one of these options, the anti-alias type for the text field on the Stage changes.

  7. Save your changes to the FLA file.

  8. Select Control > Test Movie to test your Flash document.

  9. Click the advanced_mc movie clip on the Stage.

Clicking the movie clip switches the anti-alias type from normal (the default) to advanced. When you are dealing with text fields with a smaller font size, setting the anti-aliasing to advanced can dramatically improve the readability of the text.

TIP : Advanced anti-aliasing allows font faces to be rendered at high quality at small sizes. It is best used with applications that have a lot of small text. Macromedia does not recommend advanced anti-aliasing for fonts larger than 48 points.

A sample file on your hard disk shows how to apply and manipulate anti-aliased text in an application. You use the FlashType rendering technology to create small text that's highly legible. This sample also demonstrates how text fields can scroll quickly and smoothly when you use the cacheAsBitmap property.

 

Setting tables for fonts

TOP

If you create fonts for use in SWF files or for distribution to Flash developers, you may need to set tables for fonts to control how they render on the Stage.

Advanced anti-aliasing uses adaptively sampled distance fields (ADFs) to represent the outlines that determine a glyph (a character). Flash uses two values:

  • An outside cutoff value, below which densities are set to 0.

  • An inside cutoff value, above which densities are set to a maximum density value, such as 255.

Between these two cutoff values, the mapping function is a linear curve ranging from 0 at the outside cutoff to the maximum density at the inside cutoff.

Adjusting the outside and inside cutoff values affects stroke weight and edge sharpness. The spacing between these two parameters is comparable to twice the filter radius of classic anti-aliasing methods; a narrow spacing provides a sharper edge, while a wider spacing provides a softer, more filtered edge. When the spacing is 0, the resulting density image is a bilevel bitmap. When the spacing is very wide, the resulting density image has a watercolor-like edge.

Typically, users prefer sharp, high contrast edges at small point sizes and softer edges for animated text and larger point sizes.

The outside cutoff typically has a negative value, the inside cutoff has a positive value, and their midpoint lies near 0. Adjusting these parameters to shift the midpoint toward negative infinity increases the stroke weight; shifting the midpoint toward positive infinity decreases the stroke weight.

NOTE : The outside cutoff should always be less than or equal to the inside cutoff.

Flash Player includes advanced anti-aliasing settings for ten basic fonts; and for these fonts, advanced anti-aliasing settings are provided only for the font sizes from 6 to 20. For these fonts, all sizes below 6 use the settings for 6, and all sizes above 20 use the settings for 20. Other fonts map to the supplied font data. The setAdvancedAntialiasingTable() method lets you set custom anti-aliasing data for other fonts and font sizes, or to override the default settings for the provided fonts. For more information on creating an anti-aliasing table, see the following example:

To create an advanced anti-aliasing table for an embedded font:

  1. Create a new Flash document and save it as advancedaatable.fla.

  2. Select New Font from the Library panel pop-up menu.

  3. Select Arial from the Font pop-up menu, and then set the font size to 32 points.

  4. Select both the Bold and Italics options.

  5. Enter the font name Arial (embedded) in the Name text box and click OK.

  6. Right-click (Windows) or Control-click (Macintosh) the font symbol in the library, and select Linkage.

  7. In the Linkage Properties dialog box:

    1. Type Arial-embedded in the Identifier text box.

    2. Select Export for ActionScript and Export in First Frame.

    3. Click OK.

  8. Select Frame 1 of the main Timeline, and add the following ActionScript in the Actions panel:

    import flash.text.TextRenderer;

    var arialTable:Array = new Array();

    arialTable.push({fontSize:16.0, insideCutoff:0.516, outsideCutoff:0.416});

    arialTable.push({fontSize:32.0, insideCutoff:2.8, outsideCutoff:-2.8});

    TextRenderer.setAdvancedAntialiasingTable("Arial", "bolditalic", "dark", arialTable);

    var my_fmt:TextFormat = new TextFormat();

    my_fmt.align = "justify";

    my_fmt.font = "Arial-embedded";

    my_fmt.size = 32;

    this.createTextField("my_txt", 999, 10, 10, Stage.width-20, Stage.height-20);

    my_txt.antiAliasType = "advanced";

    my_txt.embedFonts = true;

    my_txt.multiline = true;

    my_txt.setNewTextFormat(my_fmt);

    my_txt.sharpness = 0;

    my_txt.thickness = 0;

    my_txt.wordWrap = true;

    var lorem_lv:LoadVars = new LoadVars();

    lorem_lv.onData = function(src:String):Void {

    if (src != undefined) {

    my_txt.text = src + "\n\n" + src;

    } else {

    trace("error downloading text file");

    }

    };

    lorem_lv.load("http://www.helpexamples.com/flash/lorem.txt");

    The preceding code is separated into four sections. The first section of code imports the TextRenderer class and defines a new anti-aliasing table for two different sizes of the Arial font. The second section of code defines a new TextFormat object, which you use to apply text formatting to the text field (that you create in the next section of code). The next section of code creates a new text field with a my_txt instance name, enables advanced anti-aliasing, applies the text format object (created earlier), and enables multiline text and word wrapping. The final block of code defines a LoadVars object that you use to load text from an external text file, and populate the text field on the Stage.

  9. Select Control > Test movie to test the Flash document.

After the text loads from the remote server, Flash displays some text in the text field, and you can see the advanced anti-aliasing table properties applied to your text field. The embedded font on the Stage should appear like it has a slight blur effect because of the current insideCutoff and outsideCutoff values.

 

About text layout and formatting

TOP

You can control text layout and formatting by using ActionScript. The TextFormat class provides a great deal of control over how the text appears at runtime, in addition to other forms of formatting such as style sheets (see Formatting text with Cascading Style Sheet styles) and HTML text (see Using HTML-formatted text).

You can also control how characters fit on the grid by using ActionScript when you use anti-alias text in a SWF file. This helps you to control the appearance of the characters at runtime. For an example of how to use a grid fit type in your applications, see Using a grid fit type.

 

About formatting anti-alias text

TOP

Flash 8 introduces two new properties that you can use when you format text fields with advanced anti-aliasing enabled: sharpness and thickness. Sharpness refers to the amount of aliasing that is applied to the text field instance. A high value for sharpness makes the embedded font edge appear jagged and sharp. Setting sharpness to a lower value makes the font appear softer, with more blurring. Setting a font's thickness is similar to enabling bold formatting for a text field. The higher the thickness, the bolder the font appears.

The following example dynamically loads a text file and displays text on the Stage. Moving the mouse pointer along the x axis sets the sharpness between -400 and 400. Moving the mouse pointer along the y axis sets the thickness between -200 and 200.

To modify a text field's sharpness and thickness:

  1. Create a new Flash document and save it as sharpness.fla.

  2. Select New Font from the pop-up menu in the upper-right corner of the Library panel.

  3. Select Arial from the Font drop-down menu and set the font size to 24 points.

  4. Enter the font name of Arial-24 (embedded) in the Name text box and click OK.

  5. Right-click the font symbol in the library and select Linkage to open the Linkage Properties dialog box.

  6. Set the linkage identifier to Arial-24, select the Export for ActionScript and Export in First Frame check boxes, and click OK.

  7. Add the following code to Frame 1 of the main Timeline:

    var my_fmt:TextFormat = new TextFormat();

    my_fmt.size = 24;

    my_fmt.font = "Arial-24";

    this.createTextField("lorem_txt", 10, 0, 20, Stage.width, (Stage.height - 20));

    lorem_txt.setNewTextFormat(my_fmt);

    lorem_txt.text = "loading...";

    lorem_txt.wordWrap = true;

    lorem_txt.autoSize = "left";

    lorem_txt.embedFonts = true;

    lorem_txt.antiAliasType = "advanced";

    this.createTextField("debug_txt", 100, 0, 0, Stage.width, 20);

    debug_txt.autoSize = "left";

    debug_txt.background = 0xFFFFFF;

    var lorem_lv:LoadVars = new LoadVars();

    lorem_lv.onData = function(src:String) {

    lorem_txt.text = src;

    }

    lorem_lv.load("http://www.helpexamples.com/flash/lorem.txt");

    var mouseListener:Object = new Object();

    mouseListener.onMouseMove = function():Void {

    lorem_txt.sharpness = (_xmouse * (800 / Stage.width)) - 400;

    lorem_txt.thickness = (_ymouse * (400 / Stage.height)) - 200;

    debug_txt.text = "sharpness=" + Math.round(lorem_txt.sharpness) +

    ", thickness=" + Math.round(lorem_txt.thickness);

    };

    Mouse.addListener(mouseListener);

    This ActionScript code can be separated into five key sections. The first section of code defines a new TextFormat instance that will be applied to a dynamically created text field. The next two sections create two new text fields on the Stage. The first text field, lorem_txt, applies the custom text formatting object created earlier, enables embedded fonts, and sets the antiAliasType property to true. The second text field, debug_txt,displays the current sharpness and thickness values for the lorem_txt text field. The fourth section of code creates a LoadVars object, which is responsible for loading the external text file and populating the lorem_txt text field. The fifth, and final, section of code defines a mouse listener that is called whenever the mouse pointer moves on the Stage. The current values for sharpness and thickness are calculated based on the current position of the mouse pointer on the Stage. The sharpness and thickness properties are set for the lorem_txt text field, and the current values are displayed in the debug_txt text field.

  8. Select Control > Test Movie to test the document.

Move the mouse pointer along the x axis to change the text field's sharpness. Move the mouse pointer from left to right to cause the sharpness to increase and appear more jagged. Move the mouse pointer along the y axis to cause the text field's thickness to change.

A sample file on your hard disk shows how to apply and manipulate anti-aliased text in an application. You use the FlashType rendering technology to create small text that's highly legible.

This sample also demonstrates how text fields can scroll quickly and smoothly when you use the cacheAsBitmap property.

 

Using a grid fit type

TOP

When you use advanced anti-aliasing on a text field, three types of grid fitting are available:

none  Specifies no grid fitting. Horizontal and vertical lines in the glyphs are not forced to the pixel grid. This setting is usually good for animation and for large font sizes.

pixel Specifies that strong horizontal and vertical lines are fit to the pixel grid. This setting works only for left-aligned text fields. This setting generally provides the best legibility for left-aligned text.

subpixel Specifies that strong horizontal and vertical lines are fit to the subpixel grid on an LCD monitor. The subpixel setting is generally good for right-aligned and center-aligned dynamic text, and it is sometimes a useful trade-off for animation versus text quality.

The following example shows how to set a grid fit type on a text field by using ActionScript.

To set a grid fit type on a text field:

  1. Create a new Flash document and save it as gridfittype.fla.

  2. Select New Font from the pop-up menu in the upper-right corner of the Library panel.

  3. Select Arial font from the Font drop-down menu and set the font size to 10 points.

  4. Type the font name Arial-10 (embedded) in the Name text box and click OK.

  5. Right-click the font symbol in the library and select Linkage to open the Linkage Properties dialog box.

  6. Set the linkage identifier to Arial-10, and then select the Export for ActionScript and Export in First Frame check boxes.

  7. Click OK.

  8. Add the following code to Frame 1 of the main Timeline:

    var my_fmt:TextFormat = new TextFormat();

    my_fmt.size = 10;

    my_fmt.font = "Arial-10";

    var h:Number = Math.floor(Stage.height / 3);

    this.createTextField("none_txt", 10, 0, 0, Stage.width, h);

    none_txt.antiAliasType = "advanced";

    none_txt.embedFonts = true;

    none_txt.gridFitType = "none";

    none_txt.multiline = true;

    none_txt.setNewTextFormat(my_fmt);

    none_txt.text = "loading...";

    none_txt.wordWrap = true;

    this.createTextField("pixel_txt", 20, 0, h, Stage.width, h);

    pixel_txt.antiAliasType = "advanced";

    pixel_txt.embedFonts = true;

    pixel_txt.gridFitType = "pixel";

    pixel_txt.multiline = true;

    pixel_txt.selectable = false;

    pixel_txt.setNewTextFormat(my_fmt);

    pixel_txt.text = "loading...";

    pixel_txt.wordWrap = true;

    this.createTextField("subpixel_txt", 30, 0, h*2, Stage.width, h);

    subpixel_txt.antiAliasType = "advanced";

    subpixel_txt.embedFonts = true;

    subpixel_txt.gridFitType = "subpixel";

    subpixel_txt.multiline = true;

    subpixel_txt.setNewTextFormat(my_fmt);

    subpixel_txt.text = "loading...";

    subpixel_txt.wordWrap = true;

    var lorem_lv:LoadVars = new LoadVars();

    lorem_lv.onData = function(src:String):Void {

    if (src != undefined) {

    none_txt.text = "[antiAliasType=none]\n" + src;

    pixel_txt.text = "[antiAliasType=pixel]\n" + src;

    subpixel_txt.text = "[antiAliasType=subpixel]\n" + src;

    } else {

    trace("unable to load text file");

    }

    };

    lorem_lv.load("http://www.helpexamples.com/flash/lorem.txt");

    The preceding ActionScript code can be separated into five sections. The first section defines a new text format object that specifies two properties, size and font. The font property refers to the linkage identifier of the font symbol currently in the document library. The second, third, and fourth sections of code each create a new dynamic text field on the Stage and set some common properties: antiAliasType (which must be set to advanced), embedFonts (set to true), multiline, and wordWrap. Each section also applies the text format object created in an earlier section, and sets the grid fit type to normal, pixel, or subpixel. The fifth, and final, section creates a LoadVars instance, which loads the contents of an external text file into each of the text fields that you created with code.

  9. Save the document and select Control > Test movie to test the SWF file.

Each text field should be initialized with the value "loading...". After the external text file is successfully loaded, each text field displays some formatted sample text using a different grid-fit type.

TIP : The FlashType rendering technology uses grid fitting only at 0 rotation.

 

Using the TextFormat class

TOP

You can use the TextFormat class to set the formatting properties of a text field. The TextFormat class incorporates character and paragraph formatting information. Character formatting information describes the appearance of individual characters: font name, point size, color, and an associated URL. Paragraph formatting information describes the appearance of aparagraph: left margin, right margin, indentation of the first line, and left, right, or center alignment

 
To use the TextFormat class, you first create a TextFormat object and set its character and paragraph formatting styles. You then apply the TextFormat object to a text field using the TextField.setTextFormat() or TextField.setNewTextFormat() method.

The setTextFormat() method changes the text format that is applied to individual characters, to groups of characters, or to the entire body of text in a text field. Newly inserted text, however--such as text entered by a user or inserted with ActionScript--does not assume the formatting specified by a setTextFormat() call. To specify the default formatting for newly inserted text, use TextField.setNewTextFormat(). For more information, see setTextFormat (TextField.setTextFormat method) and setNewTextFormat (TextField.setNewTextFormat method) in the ActionScript 2.0 Language Reference.

To format a text field with the TextFormat class:

  1. In a new Flash document, create a text field on the Stage using the Text tool.

    Type some text in the text field on the Stage, such as Bold, italic, 24 point text.

  2. In the Property inspector, type myText_txt in the Instance Name text box, select Dynamic from the Text Type pop-up menu, and select Multiline from the Line Type pop-up menu.

  3. Select Frame 1 on the Timeline and open the Actions panel (Window > Actions).

  4. Enter the following code in the Actions panel to create a TextFormat object, set the bold and italic properties to true, and set the size property to 24:

    // Create a TextFormat object.

    var txt_fmt:TextFormat = new TextFormat();

    // Specify paragraph and character formatting.

    txt_fmt.bold = true;

    txt_fmt.italic = true;

    txt_fmt.size = 24;

  5. Apply the TextFormat object to the text field you created in step 1 by using TextField.setTextFormat():

    myText_txt.setTextFormat(txt_fmt);

    This version of setTextFormat() applies the specified formatting to the entire text field. Two other versions of this method let you apply formatting to individual characters or groups of characters. For example, the following code applies bold, italic, 24-point formatting to the first three characters you entered in the text field:

    myText_txt.setTextFormat(0, 3, txt_fmt);

  6. Select Control > Test Movie to test the application.

 

Default properties of new text fields

TOP

Text fields created at runtime with createTextField() receive a default TextFormat object with the following properties:

align = "left"

blockIndent = 0

bold = false

bullet = false

color = 0x000000

font = "Times New Roman" (default font is Times on Mac OS X)

indent = 0

italic = false

kerning = false

leading = 0

leftMargin = 0

letterSpacing = 0

rightMargin = 0

size = 12

tabStops = [] (empty array)

target = ""

underline = false

url = ""

NOTE : The default font property on the Mac OS X is Times.

 

Formatting text with Cascading Style Sheet styles

TOP

Cascading Style Sheet (CSS) styles are a way to work with text styles that can be applied to HTML or XML documents. A style sheet is a collection of formatting rules that specify how to format HTML or XML elements. Each rule associates a style name, or selector, with one or more style properties and their values. For example, the following style defines a selector named bodyText:

.bodyText {

text-align: left

}

You can create styles that redefine built-in HTML formatting tags that Flash Player uses (such as <p> and <li>). You can also create style classes that can be applied to specific HTML elements using the <p> or <span> tag's class attribute, or define new tags.

You use the TextField.StyleSheet class to work with text style sheets. Although the TextField class can be used with Flash Player 6, the TextField.StyleSheet class requires that SWF files target Flash Player 7 or later. You can load styles from an external CSS file or create them natively using ActionScript. To apply a style sheet to a text field that contains HTML- or XML-formatted text, you use the TextField.styleSheet property. The styles defined in the style sheet are mapped automatically to the tags defined in the HTML or XML document.

Using styles sheets involves the following three basic steps:

  • Create a style sheet object from the TextField.StyleSheet class (for more information see StyleSheet (TextField.StyleSheet) in the ActionScript 2.0 Language Reference).

  • Add styles to the style sheet object, either by loading them from an external CSS file or by creating new styles with ActionScript.

  • Assign the style sheet to a TextField object that contains HTML- or XML-formatted text.

For more information, see the following topics:

  • Supported CSS properties

  • Creating a style sheet object

  • Loading external CSS files

  • Creating new styles with ActionScript

  • Applying styles to a TextField object

  • Applying a style sheet to a TextArea component

  • Combining styles

  • Using style classes

  • Styling built-in HTML tags

  • An example of using styles with HTML

  • Using styles to define new tags

  • An example of using styles with XML

 

Supported CSS properties

TOP

Flash Player supports a subset of properties in the original CSS1 specification (www.w3.org/TR/REC-CSS1). The following table shows the supported CSS properties and values as well as their corresponding ActionScript property names. (Each ActionScript property name is derived from the corresponding CSS property name; the hyphen is omitted and the subsequent character is capitalized.)
 

CSS property

ActionScript property

Usage and supported values

text-align

textAlign

Recognized values are left, center, right, and justify.

font-size

fontSize

Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.

text-decoration

textDecoration

Recognized values are none and underline.

margin-left

marginLeft

Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.

margin-right

marginRight

Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.

font-weight

fontWeight

Recognized values are normal and bold.

kerning

kerning

Recognized values are true and false.

font-style

fontStyle

Recognized values are normal and italic.

letterSpacing

letterSpacing

Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.

text-indent

textIndent

Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.

font-family

fontFamily

A comma-separated list of fonts to use, in descending order of desirability. Any font family name can be used. If you specify a generic font name, it is converted to an appropriate device font. The following font conversions are available: mono is converted to _typewriter, sans-serif is converted to _sans, and serif is converted to _serif.

color

color

Only hexadecimal color values are supported. Named colors (such as blue) are not supported. Colors are written in the following format: #FF0000.

 

Creating a style sheet object

TOP

CSSs are represented in ActionScript by the TextField.StyleSheet class. This class is available only for SWF files that target Flash Player 7 or later. To create a style sheet object, call the constructor function of the TextField.StyleSheet class:

var newStyle:TextField.StyleSheet = new TextField.StyleSheet();

To add styles to a style sheet object, you can either load an external CSS file into the object or define the styles in ActionScript. See Loading external CSS files and Creating new styles with ActionScript.

 

Loading external CSS files

TOP

You can define styles in an external CSS file and then load that file into a style sheet object. The styles defined in the CSS file are added to the style sheet object. To load an external CSS file, you use the load() method of the TextField.StyleSheet class. To determine when the CSS file has finished loading, use the style sheet object's onLoad event handler.

In the following example, you create and load an external CSS file and use the TextField.StyleSheet.getStyleNames() method to retrieve the names of the loaded styles.

To load an external style sheet:

  1. In your preferred text or CSS editor, create a new file.

  2. Add the following style definitions to the file:

    .bodyText {

    font-family: Arial,Helvetica,sans-serif;

    font-size: 12px;

    }

    .headline {

    font-family: Arial,Helvetica,sans-serif;

    font-size: 24px;

    }

  3. Save the CSS file as styles.css.

  4. In Flash, create a new FLA file.

  5. In the Timeline (Window > Timeline), select Layer 1.

  6. Open the Actions panel (Window > Actions).

  7. Add the following code to the Actions panel:

    var styles:TextField.StyleSheet = new TextField.StyleSheet();

    styles.onLoad = function(success:Boolean):Void {

    if (success) {

    // display style names.

    trace(this.getStyleNames());

    } else {

    trace("Error loading CSS file.");

    }

    };

    styles.load("styles.css");

    NOTE : In the previous code snippet, this.getStyleNames() refers to the styles object you constructed in the first line of ActionScript.

  8. Save the FLA file to the same directory that contains styles.css.

  9. Test the Flash document (Control > Test Movie).

You should see the names of the two styles in the Output panel:

.bodyText,.headline

If you see "Error loading CSS file." in the Output panel, make sure the FLA file and the CSS file are in the same directory and that you typed the name of the CSS file correctly.

As with all other ActionScript methods that load data over the network, the CSS file must reside in the same domain as the SWF file that is loading the file. (See Cross-domain and subdomain access between SWF files.) For more information on using CSS with Flash, see StyleSheet (TextField.StyleSheet) in the ActionScript 2.0 Language Reference.

 

Creating new styles with ActionScript

TOP

You can create new text styles with ActionScript by using the setStyle() method of the TextField.StyleSheet class. This method takes two parameters: the name of the style and an object that defines that style's properties.

For example, the following code creates a style sheet object named styles that defines two styles that are identical to the ones you already imported (see Loading external CSS files):

var styles:TextField.StyleSheet = new TextField.StyleSheet();

styles.setStyle("bodyText",

{fontFamily: 'Arial,Helvetica,sans-serif',

fontSize: '12px'}

);

styles.setStyle("headline",

{fontFamily: 'Arial,Helvetica,sans-serif',

fontSize: '24px'}

);

 

Applying styles to a TextField object

TOP

To apply a style sheet object to a TextField object, you assign the style sheet object to the text field's styleSheet property.

textObj_txt.styleSheet = styles;

NOTE : Do not confuse the TextField.styleSheet property with the TextField.StyleSheet class. The capitalization indicates the difference.

When you assign a style sheet object to a TextField object, the following changes occur to the text field's normal behavior:

  • The text field's text and htmlText properties, and any variable associated with the text field, always contain the same value and behave identically.

  • The text field becomes read-only and cannot be edited by the user.

  • The setTextFormat() and replaceSel() methods of the TextField class no longer function with the text field. The only way to change the field is by altering the text field's text or htmlText property or by changing the text field's associated variable.

  • Any text assigned to the text field's text property, htmlText property, or associated variable is stored verbatim; anything written to one of these properties can be retrieved in the text's original form.

     

Applying a style sheet to a TextArea component

TOP

To apply a style sheet to a TextArea component, you create a style sheet object and assign it HTML styles using the TextField.StyleSheet class. You then assign the style sheet to the TextArea component's styleSheet property.

The following examples create a style sheet object, styles, and assign it to the myTextArea component instance.

Using a style sheet with a TextArea component:

  1. Create a new Flash document and save it as textareastyle.fla.

  2. Drag a TextArea component from the User Interface folder of the Components panel to the Stage and give it an instance name of myTextArea.

  3. Add the following ActionScript to Frame 1 of the main Timeline:

    // Create a new style sheet object and set styles for it.

    var styles:TextField.StyleSheet = new TextField.StyleSheet();

    styles.setStyle("html", {fontFamily:'Arial,Helvetica,sans-serif',

    fontSize:'12px',

    color:'#0000FF'});

    styles.setStyle("body", {color:'#00CCFF',

    textDecoration:'underline'});

    styles.setStyle("h1",{fontFamily:'Arial,Helvetica,sans-serif',

    fontSize:'24px',

    color:'#006600'});

    /* Assign the style sheet object to myTextArea component. Set html property to true, set styleSheet property to the style sheet object. */

    myTextArea.styleSheet = styles;

    myTextArea.html = true;

    var myVars:LoadVars = new LoadVars();

    // Define onData handler and load text to be displayed.

    myVars.onData = function(myStr:String):Void {

    if (myStr != undefined) {

    myTextArea.text = myStr;

    } else {

    trace("Unable to load text file.");

    }

    };

    myVars.load("http://www.helpexamples.com/flash/myText.htm");

    The preceding block of code creates a new TextField.StyleSheet instance that defines three styles: for the html, body, and h1 HTML tags. Next, the style sheet object is applied to the TextArea component and HTML formatting is enabled. The remaining ActionScript defines a LoadVars object that loads an external HTML file and populates the text area with the loaded text.

  4. Select Control > Test Movie to test the Flash document.

     

Combining styles

TOP

CSS styles in Flash Player are additive; that is, when styles are nested, each level of nesting can contribute style information, which is added together to result in the final formatting.

The following example shows some XML data assigned to a text field:

<sectionHeading>This is a section</sectionHeading>

<mainBody>This is some main body text, with one

<emphasized>emphatic</emphasized> word.</mainBody>

For the word emphatic in the above text, the emphasized style is nested within the mainBody style. The mainBody style contributes color, font-size, and decoration rules. The emphasized style adds a font-weight rule to these rules. The word emphatic will be formatted using a combination of the rules specified by mainBody and emphasized.

 

Using style classes

TOP

You can create style "classes" (not true ActionScript 2.0 classes) that you can apply to a <p> or <span> tag using either tag's class attribute. When applied to a <p> tag, the style affects the entire paragraph. You can also style a span of text that uses a style class using the <span> tag.

For example, the following style sheet defines two style classes: mainBody and emphasis:

.mainBody {

font-family: Arial,Helvetica,sans-serif;

font-size: 24px;

}

.emphasis {

color: #666666;

font-style: italic;

}

Within HTML text you assign to a text field, you can apply these styles to <p> and <span> tags, as shown in the following snippet:

<p class='mainBody'>This is <span class='emphasis'>really exciting!</span></p>

 

Styling built-in HTML tags

TOP

Flash Player supports a subset of HTML tags. (For more information, see Using HTML-formatted text.) You can assign a CSS style to every instance of a built-in HTML tag that appears in a text field. For example, the following code defines a style for the built-in <p> HTML tag. All instances of that tag are styled in the manner specified by the style rule.

p {

font-family: Arial,Helvetica,sans-serif;

font-size: 12px;

display: inline;

}

The following table shows which built-in HTML tags can be styled and how each style is applied:
 

Style name

How the style is applied

p

Affects all <p> tags.

body

Affects all <body> tags. The p style, if specified, takes precedence over the body style.

li

Affects all <li> bullet tags.

a

Affects all <a> anchor tags.

a:link

Affects all <a> anchor tags. This style is applied after any a style.

a:hover

Applied to an <a> anchor tag when the mouse pointer is over the link. This style is applied after any a and a:link style.

After the mouse pointer moves off the link, the a:hover style is removed from the link.

a:active

Applied to an <a> anchor tag when the user clicks the link. This style is applied after any a and a:link style.

After the mouse button is released, the a:active style is removed from the link.

 

An example of using styles with HTML

TOP

This section presents an example of using styles with HTML tags. You can create a style sheet that styles some built-in tags and defines some style classes. Then, you can apply that style sheet to a TextField object that contains HTML-formatted text.

To format HTML with a style sheet:

  1. Create a new file in your preferred text or CSS editor.

  2. Add the following style sheet definition to the file:

    p {

    color: #000000;

    font-family: Arial,Helvetica,sans-serif;

    font-size: 12px;

    display: inline;

    }

    a:link {

    color: #FF0000;

    }

    a:hover{

    text-decoration: underline;

    }

    .headline {

    color: #000000;

    font-family: Arial,Helvetica,sans-serif;

    font-size: 18px;

    font-weight: bold;

    display: block;

    }

    .byline {

    color: #666600;

    font-style: italic;

    font-weight: bold;

    display: inline;

    }

    This style sheet defines styles for two built-in HTML tags (<p> and <a>) that will be applied to all instances of those tags. It also defines two style classes (.headline and .byline) that will be applied to specific paragraphs and text spans.

  3. Save the file as html_styles.css.

  4. Create a new text file in a text or HTML editor, and save the document as myText.htm.

    Add the following text to the file:

    <p class='headline'>Flash adds FlashType rendering technology!</p><p><span class='byline'>San Francisco, CA</span>--Macromedia Inc. announced today a new version of Flash that features a brand new font rendering technology called FlashType, most excellent at rendering small text with incredible clarity and consistency across platforms. For more information, visit the

    <a href='http://www.macromedia.com'>Macromedia Flash web site.</a></p>

    NOTE : If you copy and paste this text string, make sure that you remove any line breaks that might have been added to the text string.

  5. Create a new Flash document in the Flash authoring tool.

  6. Select the first frame in Layer 1 in the Timeline (Window > Timeline).

  7. Open the Actions panel (Window > Actions), and add the following code to the Actions panel:

    this.createTextField("news_txt", 99, 50, 50, 450, 300);

    news_txt.border = true;

    news_txt.html = true;

    news_txt.multiline = true;

    news_txt.wordWrap = true;

    // Create a new style sheet and LoadVars object.

    var myVars_lv:LoadVars = new LoadVars();

    var styles:TextField.StyleSheet = new TextField.StyleSheet();

    // Location of CSS and text files to load.

    var txt_url:String = "myText.htm";

    var css_url:String = "html_styles.css";

    // Define onData handler and load text to display.

    myVars_lv.onData = function(src:String):Void {

    if (src != undefined) {

    news_txt.htmlText = src;
     

    } else {

    trace("Unable to load HTML file");

    }

    };

    myVars_lv.load(txt_url);

    // Define onLoad handler and Load CSS file.

    styles.onLoad = function(success:Boolean):Void {

    if (success) {

    /* If the style sheet loaded without error,

    then assign it to the text object,

    and assign the HTML text to the text field. */

    news_txt.styleSheet = styles;

    news_txt.text = storyText;

    } else {

    trace("Unable to load CSS file.");

    }

    };

    styles.load(css_url);

    NOTE : In this ActionScript, you are loading the text from an external file. For information on loading external data, see Working with Images, Sound, and Video.

  8. Save the file as news_html.fla in the same directory that contains the CSS file you created in step 3.

  9. Select Control > Test Movie to see the styles applied to the HTML text automatically.

 

Using styles to define new tags

TOP

If you define a new style in a style sheet, that style can be used as a tag, in the same way as you would use a built-in HTML tag. For example, if a style sheet defines a CSS style named sectionHeading, you can use <sectionHeading> as an element in any text field associated with the style sheet. This feature lets you assign arbitrary XML-formatted text directly to a text field, so that the text is automatically formatted using the rules in the style sheet.

For example, the following style sheet creates the new styles sectionHeading, mainBody, and emphasized:

.sectionHeading {

font-family: Verdana, Arial, Helvetica, sans-serif;

font-size: 18px;

display: block

}

.mainBody {

color: #000099;

text-decoration: underline;

font-size: 12px;

display: block

}

.emphasized {

font-weight: bold;

display: inline

}

You could then populate a text field associated with that style sheet with the following XML-formatted text:

<sectionHeading>This is a section</sectionHeading>

<mainBody>This is some main body text,

with one <emphasized>emphatic</emphasized> word.

</mainBody>

 

An example of using styles with XML

TOP

In this section, you create a FLA file that has XML-formatted text. You'll create a style sheet using ActionScript, rather than importing styles from a CSS file as shown in An example of using styles with HTML

To format XML with a style sheet:

  1. In Flash, create a FLA file.

  2. Using the Text tool, create a text field approximately 400 pixels wide and 300 pixels high.

  3. Open the Property inspector (Window > Properties > Properties), and select the text field.

  4. In the Property inspector, select Dynamic Text from the Text Type menu, select Multiline from the Line Type menu, select the Render Text as HTML option, and type news_txt in the Instance Name text box.

  5. On Layer 1 in the Timeline (Window > Timeline), select the first frame.

  6. To create the style sheet object, open the Actions panel (Window > Actions), and add the following code to the Actions panel:

    var styles:TextField.StyleSheet = new TextField.StyleSheet();

    styles.setStyle("mainBody", {

    color:'#000000',

    fontFamily:'Arial,Helvetica,sans-serif',

    fontSize:'12',

    display:'block'

    });

    styles.setStyle("title", {

    color:'#000000',

    fontFamily:'Arial,Helvetica,sans-serif',

    fontSize:'18',

    display:'block',

    fontWeight:'bold'

    });

    styles.setStyle("byline", {

    color:'#666600',

    fontWeight:'bold',

    fontStyle:'italic',

    display:'inline'

    });

    styles.setStyle("a:link", {

    color:'#FF0000'

    });

    styles.setStyle("a:hover", {

    textDecoration:'underline'

    });

    This code creates a new style sheet object named styles that defines styles by using the setStyle() method. The styles exactly match the ones you created in an external CSS file earlier in this chapter.

  7. To create the XML text to assign to the text field, open a text editor and enter the following text into a new document:

    <story><title>Flash now has FlashType</title><mainBody><byline>San Francisco, CA</byline>--Macromedia Inc. announced today a new version of Flash that features the new FlashType rendering technology. For more information, visit the <a href="http://www.macromedia.com">Macromedia Flash website</a></mainBody></story>

    NOTE : If you copy and paste this text string, make sure that you remove any line breaks that might have been added to the text string. Select Hidden Characters from the pop-up menu in the Actions panel to see and remove any extra line breaks.

  8. Save the text file as story.xml.

  9. In Flash, add the following code in the Actions panel, following the code in step 6.

    This code loads the story.xml document, assigns the style sheet object to the text field's styleSheet property, and assigns the XML text to the text field:

    var my_xml:XML = new XML();

    my_xml.ignoreWhite = true;

    my_xml.onLoad = function(success:Boolean):Void {

    if (success) {

    news_txt.styleSheet = styles;

    news_txt.text = my_xml;

    } else {

    trace("Error loading XML.");

    }

    };

    my_xml.load("story.xml");

    NOTE : You are loading XML data from an external file in this ActionScript. For information on loading external data, see Working with Images, Sound, and Video.

  10. Save the file as news_xml.fla in the same folder as story.xml.

  11. Run the SWF file (Control > Test Movie) to see the styles automatically applied to the text in the text field.

 

Using HTML-formatted text

TOP

Flash Player supports a subset of standard HTML tags such as <p> and <li> that you can use to style text in any dynamic or input text field. Text fields in Flash Player 7 and later also support the <img> tag, which lets you embed image files (JPEG, GIF, PNG), SWF files, and movie clips in a text field. Flash Player automatically wraps text around images embedded in text fields in much the same way that a web browser wraps text around embedded images in an HTML page. For more information, see About embedding images, SWF files, and movie clips in text fields.

Flash Player also supports the <textformat> tag, which lets you apply paragraph formatting styles of the TextFormat class to HTML-enabled text fields. For more information, see Using the TextFormat class.

 

Required properties and syntax for using HTML-formatted text

TOP

To use HTML in a text field, you must set several properties of the text field, either in the Property inspector or by using ActionScript:

  • Enable the text field's HTML formatting by selecting the Render Text as HTML option in the Property inspector or by setting the text field's html property to true.

  • To use HTML tags such as <p>, <br>, and <img>, you must make the text field a multiline text field by selecting the Multiline option in the Property inspector or by setting the text field's multiline property to true.

  • In ActionScript, set the value of TextField.htmlText to the HTML-formatted text string you want to display.

For example, the following code enables HTML formatting for a text field named headline_txt and then assigns some HTML to the text field:

this.createTextField("headline_txt", 1, 10, 10, 500, 300);

headline_txt.html = true;

headline_txt.wordWrap = true;

headline_txt.multiline = true;

headline_txt.htmlText = "<font face='Times New Roman' size='25'>This is how you assign HTML text to a text field.</font><br>It's very useful.</br>";

To render HTML correctly, you must use the correct syntax. Attributes of HTML tags must be enclosed in double (") or single (') quotation marks. Attribute values without quotation marks can produce unexpected results, such as improper rendering of text. For example, the following HTML snippet cannot be rendered properly by Flash Player because the value assigned to the align attribute (left) is not enclosed in quotation marks:

this.createTextField("myField_txt", 10, 10, 10, 400, 200);

myField_txt.html = true;

myField_txt.htmlText = "<p align=left>This is left-aligned text</p>";

If you enclose attribute values in double quotation marks, you must escape the quotation marks (\"). Either of the following ways of doing this is acceptable:

myField_txt.htmlText = "<p align='left'>This uses single quotes</p>";

myField_txt.htmlText = "<p align=\"left\">This uses escaped double quotes</p>";

myField_txt.htmlText = '<p align="left">This uses outer single quotes</p>';

myField_txt.htmlText = '<p align=\'left\'>This uses escaped single quotes</p>';

It's not necessary to escape double quotation marks if you're loading text from an external file; it's necessary only if you're assigning a string of text in ActionScript.

 

Anchor tag

TOP

The <a> tag creates a hypertext link and supports the following attributes:

  • href A string of up to 128 characters that specifies the URL of the page to load in the browser. The URL can be either absolute or relative to the location of the SWF file that is loading the page. An example of an absolute reference to a URL is http://www.macromedia.com; an example of a relative reference is /index.html.

  • target Specifies the name of the target window where you load the page. Options include _self, _blank, _parent, and _top. The _self option specifies the current frame in the current window, _blank specifies a new window, _parent specifies the parent of the current frame, and _top specifies the top-level frame in the current window.

For example, the following HTML code creates the link "Go home," which opens www.macromedia.com in a new browser window:

urlText_txt.htmlText = "<a href='http://www.macromedia.com' target='_blank'>Go home</a>";

You can use the special asfunction protocol to cause the link to execute an ActionScript function in a SWF file instead of opening a URL. For more information on the asfunction protocol, see asfunction protocol in the ActionScript 2.0 Language Reference.

You can also define a:link, a:hover, and a:active styles for anchor tags by using style sheets. See Styling built-in HTML tags.

NOTE : Absolute URLs must be prefixed with http://; otherwise, Flash treats them as relative URLs.

 

Bold tag

TOP

The <b> tag renders text as bold, as shown in the following example:

text3_txt.htmlText = "He was <b>ready</b> to leave!";

A bold typeface must be available for the font used to display the text.

 

Break tag

TOP

The <br> tag creates a line break in the text field. You must set the text field to be a multiline text field to use this tag.

In the following example, the line breaks between sentences:

this.createTextField("text1_txt", 1, 10, 10, 200, 100);

text1_txt.html = true;

text1_txt.multiline = true;

text1_txt.htmlText = "The boy put on his coat.<br />His coat was <font color='#FF0033'>red</font> plaid.";

 

Font tag

TOP

The <font> tag specifies a font or list of fonts to display the text.

The font tag supports the following attributes:

  • color Only hexadecimal color (#FFFFFF) values are supported. For example, the following HTML code creates red text:

myText_txt.htmlText = "<font color='#FF0000'>This is red text</font>";

  • face Specifies the name of the font to use. As shown in the following example, you can specify a list of comma-delimited font names, in which case Flash Player selects the first available font:

myText_txt.htmlText = "<font face='Times, Times New Roman'>Displays as either Times or Times New Roman...</font>";

If the specified font is not installed on the user's computer system or isn't embedded in the SWF file, Flash Player selects a substitute font.

  • size Specifies the size of the font, in pixels, as shown in the following example:

myText_txt.htmlText = "<font size='24' color='#0000FF'>This is blue, 24-point text</font>";

You can also use relative point sizes instead of a pixel size, such as +2 or -4.

 

Image tag

TOP

The <img> tag lets you embed external image files (JPEG, GIF, PNG), SWF files, and movie clips inside text fields and TextArea component instances. Text automatically flows around images you embed in text fields or components. To use this tag, you must set your dynamic or input text field to be multiline and to wrap text.

To create a multiline text field with word wrapping, do one of the following:

  • In the Flash authoring environment, select a text field on the Stage and then, in the Property inspector, select Multiline from the Text Type menu.

  • For a text field created at runtime with createTextField (MovieClip.createTextField method), set the new text field instance's multiline (TextField.multiline property) and multiline (TextField.multiline property) properties to true.

The <img> tag has one required attribute, src, which specifies the path to an image file, a SWF file, or the linkage identifier of a movie clip symbol in the library. All other attributes are optional.

The <img> tag supports the following attributes:

  • src  Specifies the URL to an image or SWF file, or the linkage identifier for a movie clip symbol in the library. This attribute is required; all other attributes are optional. External files (JPEG, GIF, PNG, and SWF files) do not show until they are downloaded completely.

  • id Specifies the name for the movie clip instance (created by Flash Player) that contains the embedded image file, SWF file, or movie clip. This is useful if you want to control the embedded content with ActionScript.

  • width The width of the image, SWF file, or movie clip being inserted, in pixels.

  • height The height of the image, SWF file, or movie clip being inserted, in pixels.

  • align Specifies the horizontal alignment of the embedded image within the text field. Valid values are left and right. The default value is left.

  • hspace Specifies the amount of horizontal space that surrounds the image where no text appears. The default value is 8.

  • vspace Specifies the amount of vertical space that surrounds the image where no text appears. The default value is 8. 

 

Italic tag

TOP

The <i> tag displays the tagged text in italics, as shown in the following code:

That is very <i>interesting</i>.

This code example would render as follows:

That is very interesting.

An italic typeface must be available for the font used.

 

List item tag

TOP

The <li> tag places a bullet in front of the text that it encloses, as shown in the following code:

Grocery list:

<li>Apples</li>

<li>Oranges</li>

<li>Lemons</li>

This code example would render as follows:

Grocery list:

  • Apples

  • Oranges

  • Lemons

NOTE : Ordered and unordered lists (<ol> and <ul> tags) are not recognized by Flash Player, so they do not modify how your list is rendered. All list items use bullets.

 

Paragraph tag

TOP

The <p> tag creates a new paragraph. You must set the text field to be a multiline text field to use this tag.

The <p> tag supports the following attributes:

  • align Specifies alignment of text within the paragraph; valid values are left, right, justify, and center.

  • class Specifies a CSS style class defined by a TextField.StyleSheet object. (For more information, see Using style classes.)

The following example uses the align attribute to align text on the right side of a text field.

this.createTextField("myText_txt", 1, 10, 10, 400, 100);

myText_txt.html = true;

myText_txt.multiline = true;

myText_txt.htmlText = "<p align='right'>This text is aligned on the right side of the text field</p>";

The following example uses the class attribute to assign a text style class to a <p> tag:

var myStyleSheet:TextField.StyleSheet = new TextField.StyleSheet();

myStyleSheet.setStyle(".blue", {color:'#99CCFF', fontSize:18});

this.createTextField("test_txt", 10, 0, 0, 300, 100);

test_txt.html = true;

test_txt.styleSheet = myStyleSheet;

test_txt.htmlText = "<p class='blue'>This is some body-styled text.</p>.";

 

Text format tag

TOP

The <textformat> tag lets you use a subset of paragraph formatting properties of the TextFormat class within HTML text fields, including line leading, indentation, margins, and tab stops. You can combine <textformat> tags with the built-in HTML tags.

The <textformat> tag has the following attributes:

  • blockindent Specifies the block indentation in points; corresponds to TextFormat.blockIndent. (See blockIndent (TextFormat.blockIndent property) in the ActionScript 2.0 Language Reference.)

  • indent Specifies the indentation from the left margin to the first character in the paragraph; corresponds to TextFormat.indent. Lets you use negative integers. (See indent (TextFormat.indent property) in the ActionScript 2.0 Language Reference.)

  • leading Specifies the amount of leading (vertical space) between lines; corresponds to TextFormat.leading. Lets you use negative integers. (See leading (TextFormat.leading property) in the ActionScript 2.0 Language Reference.)

  • leftmargin Specifies the left margin of the paragraph, in points; corresponds to TextFormat.leftMargin. (See leftMargin (TextFormat.leftMargin property) in the ActionScript 2.0 Language Reference.)

  • rightmargin Specifies the right margin of the paragraph, in points; corresponds to TextFormat.rightMargin. (See rightMargin (TextFormat.rightMargin property) in the ActionScript 2.0 Language Reference.)

  • tabstops Specifies custom tab stops as an array of non-negative integers; corresponds to TextFormat.tabStops. (See tabStops (TextFormat.tabStops property) in the ActionScript 2.0 Language Reference.)

The following table of data with boldfaced row headers is the result of the code example in the procedure that follows:

Name

Age

Occupation

Rick

33

Detective

AJ

34

Detective

 

To create a formatted table of data using tab stops:

  1. Create a new Flash document, and save it as tabstops.fla.

  2. In the Timeline, select the first frame on Layer 1.

  3. Open the Actions panel (Window > Actions), and enter the following code in the Actions panel:

    // Create a new text field.

    this.createTextField("table_txt", 99, 50, 50, 450, 100);

    table_txt.multiline = true;

    table_txt.html = true;

    // Creates column headers, formatted in bold, separated by tabs.

    var rowHeaders:String = "<b>Name\tAge\tOccupation</b>";

    // Creates rows with data.

    var row_1:String = "Rick\t33\tDetective";

    var row_2:String = "AJ\t34\tDetective";

    // Sets two tabstops, at 50 and 100 points.

    table_txt.htmlText = "<textformat tabstops='[50,100]'>";

    table_txt.htmlText += rowHeaders;

    table_txt.htmlText += row_1;

    table_txt.htmlText += row_2 ;

    table_txt.htmlText += "</textformat>";

    The use of the tab character escape sequence (\t) adds tabs between each column in the table. You append text using the += operator.

  4. Select Control > Test Movie to view the formatted table.

 

Underline tag

TOP

The <u> tag underlines the tagged text, as shown in the following code:

This is <u>underlined</u> text.

This code would render as follows:

 

About supported HTML entities

TOP


HTML entities help you display certain characters in HTML formatted text fields, so that they are not interpreted as HTML. For example, you use less-than (<) and greater-than (>) characters to enclose HTML tags, such as <img> and <span>. To display less-than or greater-than characters in HTML-formatted text fields in Flash, you need to substitute HTML entities for those characters. The following ActionScript creates an HTML formatted text field on the Stage and uses HTML entities to display the string "<b>" without having the text appear in bold:

this.createTextField("my_txt", 10, 100, 100, 100, 19);

my_txt.autoSize = "left";

my_txt.html = true;

my_txt.htmlText = "The &lt;b&gt; tag makes text appear <b>bold</b>.";

At runtime, the previous code example in Flash displays the following text on the Stage:

The <b> tag makes text appear bold.

In addition to the greater-than and less-than symbols, Flash also recognizes other HTML entities that are listed in the following table.

 

Entity

Description

&lt;

< (less than)

&gt;

> (greater than)

&amp;

& (ampersand)

&quot;

" (double quotes)

&apos;

' (apostrophe, single quote)

Flash also supports explicit character codes, such as &#39; (ampersand - ASCII) and &#x0026; (ampersand - Unicode).

The following ActionScript demonstrates how you can use ASCII or Unicode character codes to embed a tilde (~) character:

this.createTextField("my_txt", 10, 100, 100, 100, 19);

my_txt.autoSize = "left";

my_txt.html = true;

my_txt.htmlText = "&#126;"; // tilde (ASCII)

my_txt.htmlText += "\t"

my_txt.htmlText += "&#x007E;"; // tilde (Unicode)

 

About embedding images, SWF files, and movie clips in text fields

TOP

In Flash Player 7 and later, you can use the <img> tag to embed image files (JPEG, GIF, PNG), SWF files, and movie clips inside dynamic and input text fields, and TextArea component instances. (For a full list of attributes for the <img> tag, see Image tag.)

Flash displays media embedded in a text field at full size. To specify the dimensions of the media you are embedding, use the <img> tag's height and width attributes. (See About specifying height and width values.)

In general, an image embedded in a text field appears on the line following the <img> tag. However, when the <img> tag is the first character in the text field, the image appears on the first line of the text field.

 

Embedding SWF and image files

TOP


To embed an image or SWF file in a text field, specify the absolute or relative path to the image (GIF, JPEG, or PNG) or SWF file in the <img> tag's src attribute. For example, the following example inserts a GIF file that's located in the same directory as the SWF file (a relative address, on or offline).

Embedding an image in a text field:

  1. Create a new Flash document, and save it as embedding.fla.
  2. Add the following ActionScript to Frame 1 of the main Timeline:

    this.createTextField("image1_txt", 10, 50, 50, 450, 150);

    image1_txt.html = true;

    image1_txt.htmlText = "<p>Here's a picture from my vacation:<img src='beach.gif'>";

    The preceding code creates a new dynamic text field on the Stage, enables HTML formatting, and adds some text and a local image to the text field.

  3. Add the following ActionScript below the code added in the previous step:

    this.createTextField("image2_txt", 20, 50, 200, 400, 150);

    image2_txt.html = true;

    image2_txt.htmlText = "<p>Here's a picture from my garden:<img src='http://www.helpexamples.com/flash/images/image2.jpg'>";

    You can also insert an image by using an absolute address. The preceding code inserts a JPEG file that's located in a directory that's on a server. The SWF file that contains this code might be on your hard disk or on a server.

  4. Save the document and select Control > Test Movie to test the document.

The upper text field should have a sentence of text and most likely an error message in the Output panel saying that Flash was unable to locate a file named beach.gif in the current directory.

The lower text field should have a sentence of text and an image of a flower that was loaded from the remote server.

Copy a GIF image to the same directory as the FLA and rename the image to beach.gif and select Control > Test Movie to retest the Flash document.

NOTE : When using absolute URLs, you must make sure that your URL is prefixed with http://.

 

Embedding movie clip symbols

TOP


To embed a movie clip symbol in a text field, you specify the symbol's linkage identifier for the <img> tag's src attribute. (For information on defining a linkage identifier, see Attaching a movie clip symbol to the Stage.)

For example, the following code inserts a movie clip symbol with the linkage identifier symbol_ID into a dynamic text field with the instance name textField_txt.

To embed a movie clip into a text field:

  1. Create a new Flash document and save it as embeddedmc.fla.
  2. Draw a new shape on the Stage, or select File > Import > Import to Stage and select an image that is roughly 100 pixels wide by 100 pixels high.
  3. Convert the shape or image imported in the previous step by selecting it on the Stage and pressing F8 to open the Convert to Symbol dialog box.
  4. Set the behavior to Movie Clip and enter a descriptive symbol name. Select the upper-left square of the registration point grid, and click Advanced to switch to advanced mode if you haven't already done so.
  5. Select the Export of ActionScript and Export in First Frame check boxes.
  6. Enter the linkage identifier img_id in the Identifier text box and then click OK.
  7. Add the following ActionScript to Frame 1 of the main Timeline:

    this.createTextField("textField_txt", 10, 0, 0, 300, 200);

    textField_txt.html = true;

    textField_txt.htmlText = "<p>Here's a movie clip symbol:<img src='img_id'>";

    For an embedded movie clip to be displayed properly and completely, the registration point for its symbol should be at point (0,0).

  8. Save your changes to the Flash document.
  9. Select Control > Test Movie to test the Flash document.

 

About specifying height and width values

TOP

If you specify width and height attributes for an <img> tag, space is reserved in the text field for the image file, SWF file, or movie clip. After an image or SWF file is downloaded completely, it appears in the reserved space. Flash scales the media up or down, according to the values you specify for height and width. You must enter values for both the height and width attributes to scale the image.

If you don't specify values for height and width, no space is reserved for the embedded media. After an image or SWF file has downloaded completely, Flash inserts it into the text field at full size and rebreaks text around it.

NOTE : If you are dynamically loading your images into a text field containing text, it is good practice to specify the width and height of the original image so the text properly wraps around the space you reserve for your image.

 

Controlling embedded media with ActionScript

TOP


Flash creates a new movie clip for each <img> tag and embeds that movie clip within the TextField object. The <img> tag's id attribute lets you assign an instance name to the movie clip that is created. This lets you control that movie clip with ActionScript.

The movie clip that Flash creates is added as a child movie clip to the text field that contains the image.

For example, the following example embeds a SWF file in a text field.

To embed a SWF file in a text field:

  1. Create a new Flash document.
  2. Resize the document's Stage size to 100 pixels by 100 pixels.
  3. Use the Rectangle tool to draw a red square on the Stage.
  4. Resize the square to 80 pixels by 80 pixels by using the Property inspector, and then move the shape to the center of the Stage.
  5. Select Frame 20 on the Timeline and then press F7 (Windows or Macintosh) to insert a new blank keyframe.
  6. Use the Oval tool to draw a blue circle on the Stage on Frame 20.
  7. Resize the circle to 80 pixels by 80 pixels by using the Property inspector, and then move it to the center of the Stage.
  8. Click a blank frame between Frame 1 and 20, and set the tween type to Shape in the Property inspector.
  9. Save the current document as animation.fla.
  10. Select Control > Test Movie to preview the animation.

    The SWF file is created in the same directory as the FLA. For this exercise to work correctly, you need the SWF file to generate so that you can load it into a separate FLA file.

  11. Create a new FLA file and save it as animationholder.fla.

    Save the file in the same folder as the animation.fla file you created previously.

  12. Add the following ActionScript code to Frame 1 of the main Timeline:

    this.createTextField("textField_txt", 10, 0, 0, 300, 200);

    textField_txt.html = true;

    textField_txt.htmlText = "Here's an interesting animation: <img src='animation.swf' id='animation_mc'>";

    In this case, the fully qualified path to the newly created movie clip is textField_txt.animation_mc.

  13. Save your changes to the Flash document and then select Control > Test Movie to preview the animation within the text field.

To control the SWF file as it plays in a text field, complete the next exercise.

To control a SWF file that plays in a text field:

  1. Follow the steps in the first procedure under Controlling embedded media with ActionScript.
  2. Create a button instance on the Stage and give it the instance name stop_btn in the Property inspector.
  3. Add the following ActionScript code beneath the existing code in Frame 1 of the main Timeline:

    stop_btn.onRelease = function() {

    textField_txt.animation_mc.stop();

    };

  4. Select Control > Test Movie to test the application.

Now, whenever you click the stop_btn button instance, the timeline of the animation nested within the text field stops.

 

About making hypertext links out of embedded media

TOP


To make a hypertext link out of an embedded image file, SWF file, or movie clip, enclose the <img> tag in an <a> tag:

textField_txt.htmlText = "Click the image to return home<a href='home.htm'><img src='home.jpg'></a>";

When the mouse pointer is over an image, SWF file, or movie clip that is enclosed by <a> tags, the mouse pointer turns into a "pointing hand" icon, the same as it does with standard hypertext links. Interactivity, such as mouse clicks and keypresses, does not register in SWF files and movie clips that are enclosed by <a> tags.

 

Example: Creating scrolling text

TOP

You can use several methods to create scrolling text in Flash. You can make dynamic and input text fields scrollable by selecting the Scrollable option from the Text menu or the context menu, or by pressing Shift and double-clicking the text field handle.

You can use the scroll and maxscroll properties of the TextField object to control vertical scrolling and the hscroll and maxhscroll properties to control horizontal scrolling in a text field. The scroll and hscroll properties specify the current vertical and horizontal scrolling positions, respectively; you can read and write these properties. The maxscroll and maxhscroll properties specify the maximum vertical and horizontal scrolling positions, respectively; you can only read these properties.

The TextArea component provides an easy way to create scrolling text fields with a minimum amount of scripting. For more information, see TextArea component in the Components Language Reference.

To create a scrollable dynamic text field:

Do one of the following:

  • Shift-double-click the handle on the dynamic text field.

  • Select the dynamic text field with the Selection tool, and select Text > Scrollable.

  • Select the dynamic text field with the Selection tool. Right-click (Windows) or Control-click (Macintosh) the dynamic text field, and select Text > Scrollable.

To use the scroll property to create scrolling text:

  1. Do one of the following:

    1. Use the Text tool to drag a text field on the Stage. Assign the text field the instance name textField_txt in the Property inspector.

    2. Use ActionScript to create a text field dynamically with the MovieClip.createTextField() method. Assign the text field the instance name textField_txt as a parameter of the method.

    NOTE : If you are not dynamically loading text into the SWF file, select Text > Scrollable from the main menu.

  2. Create an Up button and a Down button, or select Window > Common Libraries > Buttons, and drag buttons to the Stage.

    You will use these buttons to scroll the text up and down.

  3. Select the Down button on the Stage and type down_btn into the Instance Name text box.

  4. Select the Up button on the Stage and type up_btn into the Instance Name text box.

  5. Select Frame 1 on the Timeline, and, in the Actions panel (Window > Actions), enter the following code to scroll the text down in the text field:

    down_btn.onPress = function() {

    textField_txt.scroll += 1;

    };

  6. Following the ActionScript in step 5, enter the following code to scroll the text up:

up_btn.onPress = function() {

textField_txt.scroll -= 1;

};

Any text that loads into the textField_txt text field can be scrolled using the up and down buttons.

 

About strings and the String class

TOP


In programming, a string is an ordered series of characters. You use strings often in your Flash documents and class files to display text in applications, such as within text fields. Also, you can store values as strings that you can use in an application for a variety of purposes. You can put strings directly in your ActionScript code by placing quotation marks around the characters of data. For more information on creating strings, see Creating strings. For information on using text fields, see Using the TextField class.

You can associate each character with a specified character code, which you can also optionally use to display text. For example, the character "A" is represented by the Unicode character code 0041, or 65 in ASCII (American Standard Code for Information Interchange). For more information on character codes and code charts, see www.unicode.org/charts. As you can see, the way you represent strings in a Flash document depends a lot on the character set you choose, and the way you encode characters.

Character encoding refers to the code, or method, for representing a set of characters in a language to representative codes, such as numeric values. The character code (as mentioned in the previous paragraph) is the table of mapped values (such as the ASCII table, where A equals 65). The encoding method deciphers it in a computer program.

For example, each letter in the English language would have a representative numerical code in a character encoding. ASCII encodes each letter, number, and some symbols to 7-bit binary versions of each integer. ASCII is a character set consisting of 95 printable characters and numerous control characters; ASCII is used by computers to represent text.

Like ASCII, Unicode is another way to associate a code with each letter of the alphabet. Because ASCII cannot support large character sets, such as Chinese, the Unicode Standard is a valuable standard to encode languages. Unicode is the standard for character sets that can represent any language set. It is a standard that exists to help development in multiple languages.

The character code designates what character it represents, and the standard attempts to provide a universal way to encode characters that are part of any language. Strings could be displayed on any computer system, or platform, or software used. Then, it is up to the program involved (such as Flash or a web browser) to display the character glyph (its visual appearance).

Over the years, the number of characters that Unicode supports has expanded to add support for more (and larger) languages. The character encodings are called Unicode Transformation Format (UTF) and Universal Character Set (UCS), which include UTF-8, UTF-16, and UTF-32. The numbers in UTF encoding represent the number of bits in a unit, and the numbers in a UCS encoding represent bytes.

  • UTF-8 is the standard encoding for exchanging text, such as online mail systems. UTF is an 8-bit system.
  • UTF-16 is commonly used for internal processing.

Strings can be of various lengths in your applications. You can determine the length of your string, although this might vary, depending on what language you're using. Also, you might encounter a terminating character at the end of a string, and this null character doesn't have a value. This terminating character is not an actual character, but you can use it to determine when a string ends. For example, if you're working with socket connections, you might watch for the terminating character to know the end of a string (such as in a chat program).

 

About the Strings panel

TOP

The Strings panel lets you create and update multilingual content. You can specify content for text fields that span multiple languages, and have Flash automatically determine the content that should appear in a certain language based on the language of the computer that is running Flash Player.

For general information on the Strings panel, and how to use it in your applications, see the following topics in Using Flash:

  • Authoring multilanguage text with the Strings panel

  • About editing strings in the Strings panel

  • Translating text in the Strings panel or an XML file

  • Importing an XML file into the Strings panel

     

Using the Locale class

TOP


The Locale class (mx.lang.Locale) allows you to control how multilanguage text is displayed in a Flash application at runtime. With the Strings panel, you can use string IDs instead of string literals in dynamic text fields, which allows you to create a SWF file that displays text loaded from a language-specific XML file. You can use the following methods to display the language-specific strings contained in the XML Localization Interchange File Format (XLIFF) files.

Automatically at runtime Flash Player replaces string IDs with strings from the XML file, which matches the default system language code that is returned by language (capabilities.language property).

Manually using stage language String IDs are replaced by strings when the SWF file compiles, and cannot be changed by Flash Player.

Using ActionScript at runtime You can control string ID replacement by using ActionScript, which is controlled at runtime. This option gives you control over both the timing and the language of string ID replacement.

You can use the properties and methods of the Locale class when you want to replace the string IDs by using ActionScript to control the application when it plays in Flash Player. For a demonstration of how to use the Locale class, see the following procedure.

To use the Locale class to create multilanguage sites:

  1. Create a new Flash document and save it as locale.fla.
  2. Open the Strings panel (Window > Other Panels > Strings) and click Settings.
  3. Select two languages, en (English) and fr (French), and click Add to add the languages to the Active languages pane.
  4. Select the Via ActionScript at Runtime option, set the default runtime language to French, and click OK.
  5. Drag a ComboBox component from the User Interface folder of the Components panel (Window > Components) onto the Stage and give it the instance name lang_cb.
  6. Create a dynamic text field on the Stage using the Text tool and give the text field the instance name greeting_txt.
  7. With the text field selected on the Stage, type a string identifier of greeting in the ID text box of the Strings panel and click Apply.

    You'll notice that Flash converts the greeting string into IDS_GREETING.

  8. In the String panel's grid, type the string hello in the en column.
  9. Type the string bonjour in the fr column.

    You use these strings when you use the lang_cb combo box to change the language on the Stage.

  10. Add the following ActionScript to Frame 1 of the main Timeline:

    import mx.lang.Locale;

    Locale.setLoadCallback(localeListener);

    lang_cb.dataProvider = Locale.languageCodeArray.sort();

    lang_cb.addEventListener("change", langListener);

    greeting_txt.autoSize = "left";

    Locale.loadLanguageXML(lang_cb.value);


    function langListener(eventObj:Object):Void {

    Locale.loadLanguageXML(eventObj.target.value);

    }

    function localeListener(success:Boolean):Void {

    if (success) {

    greeting_txt.text = Locale.loadString("IDS_GREETING");

    } else {

    greeting_txt.text = "unable to load language XML file.";

    }

    }

    The preceding ActionScript is split into two sections. The first section of code imports the Locale class and specifies a callback listener that is called whenever a language XML file is finished loading. Next, the lang_cb combo box is populated with a sorted array of available languages. Whenever the lang_cb value changes, Flash's event dispatcher triggers the langListener() function, which loads the specified-language XML file. The second section of code defines two functions, langListener(), and localeListener(). The first function, langListener(), is called whenever the lang_cb combo box's value is changed by the user. The second function, localeListener(), is called whenever a language XML file is finished loading. The function checks if the load was successful, and if so, sets the text property of the greeting_txt instance to the greeting for the selected language.

  11. Select Control > Test Movie to test the Flash document.

TIP : The XML file that you use must use the XML Localization Interchange File Format (XLIFF).

CAUTION : The Locale class is different from the other classes in the ActionScript 2.0 Language Reference, since it is not part of the Flash Player. Because this class installed in the Flash Authoring classpath, it is automatically compiled into your SWF files. Using the Locale class increases the SWF file size slightly, because the class must be compiled into the SWF file.

 

Using an input method editor

TOP

An input method editor (IME) lets users type non-ASCII text characters in Asian languages such as Chinese, Japanese, and Korean. The IME class in ActionScript lets you directly manipulate the operating system's IME in the Flash Player application that is running on a client computer.

Using ActionScript, you can determine the following:

  • Whether an IME is installed on the user's computer.

  • Whether the IME is enabled or disabled on the user's computer.

  • Which conversion mode the current IME is using.

The IME class can determine which conversion mode the current IME is using: for example, if the Japanese IME is active, you can determine if the conversion mode is Hiragana, Katakana (and so on) using the System.IME.getConversionMode() method. You can set it with the System.IME.setConversionMode() method.

NOTE : Curently, you cannot tell which IME is active (if any), or change from one IME to another (for instance, English to Japanese or Korean to Chinese)

You can also disable or enable the IME by using your application at runtime, and perform other functions, depending on the user's operating system. You can check whether a system has an IME by using the System.capabilities.hasIME property. The next example shows how to determine whether the user has an IME installed and active.

To determine whether the user has an IME installed and active:

  1. Create a new Flash document and save it as ime.fla.

  2. Add the following ActionScript to Frame 1 of the main Timeline:

    if (System.capabilities.hasIME) {

    if (System.IME.getEnabled()) {

    trace("You have an IME installed and enabled.");

    } else {

    trace("You have an IME installed but not enabled.");

    }

    } else {

    trace("Please install an IME and try again.");

    }

    The preceding code first checks whether the current system has an IME installed. If an IME is installed, Flash checks whether it is currently enabled.

  3. Select Control > Test Movie to test the document.

A message appears in the Output panel stating whether you have an IME installed and currently active.

You can also use the IME class to enable and disable the IME in Flash at runtime. The following example requires that you have an IME installed on your system. For more information on installing an IME on your specific platform, see the following links:

You can enable and disable an IME while the SWF file plays, as shown in the following example.

To enable and disable an input method editor at runtime:

  1. Create a new Flash document and save it as ime2.fla.

  2. Create two button symbol instances on the Stage and give them the instance names enable_btn and disable_btn.

  3. Add the following ActionScript to Frame 1 of the main Timeline:

    checkIME();

    var my_fmt:TextFormat = new TextFormat();

    my_fmt.font = "_sans";

    this.createTextField("ime_txt", 10, 100, 10, 320, 240);

    ime_txt.border = true;

    ime_txt.multiline = true;

    ime_txt.setNewTextFormat(my_fmt);

    ime_txt.type = "input";

    ime_txt.wordWrap = true;

    enable_btn.onRelease = function() {

    System.IME.setEnabled(true);

    };

    disable_btn.onRelease = function() {

    System.IME.setEnabled(false);

    };

    function checkIME():Boolean {

    if (System.capabilities.hasIME) {

    if (System.IME.getEnabled()) {

    trace("You have an IME installed and enabled.");

    return true;

    } else {

    trace("You have an IME installed but not enabled.");

    return false;

    }

    } else {

    trace("Please install an IME and try again.");

    return false;

    }

    }

    The preceding code is separated into five sections. The first section calls the checkIME() method, which displays a message in the Output panel if the system has an IME installed or active.

    The second section defines a custom text-format object, which sets the font to _sans. The third section creates an input text field and applies the custom text format. The fourth section creates some event handlers for the enable_btn and disable_btn instances created in an earlier step. The fifth, and final, section of code defines the custom checkIME() function, which checks whether the current system has an IME installed and if so, whether or not the IME is active.

  4. Save the FLA file and select Control > Test Movie to test the document.

NOTE : This example requires that you have an IME installed on your system. For information on installing an IME, see the links that precede this example.

Type some text into the input text field on the Stage. Switch your IME to a different language and type in the input text field again. Flash Player inputs characters by using the new IME. If you click the disable_btn button on the Stage, Flash reverts to using the previous language and ignores the current IME settings.

 

About the String class

TOP


A string is also a class and data type in the core ActionScript language. The String data type represents a sequence of 16-bit characters that might include letters, numbers, and punctuation marks. Strings are stored as Unicode characters, using the UTF-16 format. An operation on a String value returns a new instance of the string. The default value for a variable declared with the String data type is null.

The String class contains methods that let you work with text strings. Strings are important in working with many objects, and the methods described in this chapter are useful in working with strings used in many objects, such as TextField, XML, ContextMenu, and FileReference instances.

The String class is a wrapper for the String primitive data type, and provides methods and properties that let you manipulate primitive string values. You can convert the value of any object into a string by using the String() function. All the methods of the String class, except for concat(), fromCharCode(), slice(), and substr(), are generic, which means the methods call the toString() function before they perform their operations, and you can use these methods with other non-String objects.

Because all string indexes are zero-based, the index of the last character for any myStr string is myStr.length - 1.

 

Creating strings

TOP


You can call any of the methods of the String class by using the new String() constructor method or by using a string literal value. If you specify a string literal, the ActionScript interpreter automatically converts it to a temporary String object, calls the method, and discards the temporary String object. You can also use the String.length property with a string literal.

Do not confuse a string literal with a String object. For more information on string literals and the String object, see About literals.

In the following example, the line of code creates the firstStr string literal. To declare a string literal, use single straight quotation mark (') or double straight quotation mark (") delimiters.

To create and use strings:

  1. Create a new Flash document and save it as strings.fla.
  2. Add the following ActionScript to Frame 1 of the main Timeline:

    var firstStr:String = "foo";

    var secondStr:String = new String("foo");

    trace(firstStr == secondStr); // true

    var thirdStr:String;

    trace(thirdStr); // undefined

    This code defines three String objects, one that uses a string literal, one that uses the new operator, and the other without an initial value. Strings can be compared by using the equality (==) operator, as shown in the third line of code. When referring to variables, you specify the data type only when the variable is being defined.

  3. Select Control > Test Movie to test the document.

Always use string literals unless you specifically need to use a String object. For more information on string literals and the String object, see About literals.

To use single straight quotation mark (') and double straight quotation mark (") delimiters within a single string literal, use the backslash character (\) to escape the character. The following two strings are equivalent:

var firstStr:String = "That's \"fine\"";

var secondStr:String = 'That\'s "fine"';

Remember that you cannot use "curly quotation mark" or "special quotation mark" characters within your ActionScript code; they are different from the straight quotation marks (') and (") that you can use in your code. When you paste text from another source into ActionScript, such as the web or a Word document, be sure to use straight quote delimiters.

 

About the escape character  

TOP

You can use the backslash escape character (\), to define other characters in string literals.

Escape sequence

Description

\b

The backspace character.

\f

The form feed character.

\n

The newline character.

\r

The carriage return.

\t

The tab character.

\unnnn

The Unicode character with the character code specified by the hexidecimal number nnnn. For example, \u263a is the smile character.

\xnn

The ASCII character with the character code specified by the hexidecimal number nn.

\'

A single quotation mark.

\"

A double quotation mark.

\\

A single backslash character.

 

Analyzing and comparing characters in strings

TOP

Every character in a string has an index position in the string (an integer). The index position of the first character is 0. For example, in the string yellow, the character y is in position 0 and the character w is in position 5.

Every string has a length property, which is equal to the number of characters in the string:

var companyStr:String = "macromedia";

trace(companyStr.length); // 10

An empty string and a null string both have a length of zero:

var firstStr:String = new String();

trace(firstStr.length); // 0

var secondStr:String = "";

trace(secondStr.length); // 0

If a string doesn't contain a value, its length is set to undefined:

var thirdStr:String;

trace(thirdStr.length); // undefined

WARNING : If your string contains a null byte character (\0), the string value will be truncated.

You can also use character codes to define a string. For more information on character codes and character encoding, see About strings and the String class.

The following example creates a variable named myStr and sets the string's value based on ASCII values passed to the String.fromCharCode() method:

var myStr:String = String.fromCharCode(104,101,108,108,111,32,119,111,114,108,100,33);

trace(myStr); // hello world!

Each number listed in the fromCharCode() method in the previous code represents a single character. For example, the ASCII value 104 represents a lowercase h, and the ASCII value 32 represents the space character.

You can also use the String.fromCharCode() method to convert Unicode values, although the unicode value must be converted from hexidecimal to decimal values, as shown in the following ActionScript:

// Unicode 0068 == "h"

var letter:Number = Number(new Number(0x0068).toString(10));

trace(String.fromCharCode(letter)); // h

You can examine the characters in various positions in a string, as in the following example.

To loop over a string:

  1. Create a new Flash document.

  2. Add the following ActionScript to Frame 1 of the main Timeline:

    var myStr:String = "hello world!";

    for (var i:Number = 0; i < myStr.length; i++) {

    trace(myStr.charAt(i));

    }

  3. Select Control > Test Movie to preview your Flash document. You should see each character traced to the Output panel on a separate line.

  4. Modify the existing ActionScript code so that it traces the ASCII value for each character:

    var myStr:String = "hello world!";

    for (var i:Number = 0; i < myStr.length; i++) {

    trace(myStr.charAt(i) + " - ASCII=" + myStr.charCodeAt(i));

    }

  5. Save the current Flash document and select Control > Test Movie to preview the SWF file.

When you run this code, the following is displayed in the Output panel:

h - ASCII=104

e - ASCII=101

l - ASCII=108

l - ASCII=108

o - ASCII=111

- ASCII=32

w - ASCII=119

o - ASCII=111

r - ASCII=114

l - ASCII=108

d - ASCII=100

! - ASCII=33

TIP : You can also split a string into an array of characters by using the String.split() method and entering an empty string ("") as a delimiter; for example, var charArray:Array = myStr.split("");

You can use operators to compare strings. For information on using operators with strings, see About using operators with strings.

You can use these operators with conditional statements, such as if and while. The following example uses operators and strings to make a comparison.

To compare two strings:

  1. Create a new Flash document and save it as comparestr.fla.

  2. Add the following ActionScript to Frame 1 of the main Timeline:

    var str1:String = "Apple";

    var str2:String = "apple";

    if (str1 < str2) {

    trace("Uppercase letters sort first.");

    }

  3. Save the Flash document and select Control > Test Movie to test the SWF file.

You can use the equality (==) and inequality (!=) operators to compare strings with other types of objects, as shown in the following example.

To compare strings to other data types:

  1. Create a new Flash document and save it as comparenum.fla.

  2. Add the following ActionScript to Frame 1 of the main Timeline:

    var myStr:String = "4";

    var total:Number = 4;

    if (myStr == total) {

    trace("Types are converted.");

    }

  3. Save the Flash document and select Control > Test Movie to test the SWF file.

When comparing two different data types (such as strings and numbers), Flash tries to convert the data types so that a comparison can be made.

Use the strict equality (===) and strict inequality (!==) operators to verify that both comparison objects are of the same type. The following example uses strict comparison operators to ensure that Flash doesn't try to convert data types while trying to compare values.

To force strict data type comparisons:

  1. Create a new Flash document and save it as comparestrict.fla.

  2. Add the following ActionScript to Frame 1 of the main Timeline:

    var str1:String = "4";

    var str2:String = "5";

    var total:Number = 4;

    if (str1 !== total) {

    trace("Types are not converted.");

    }

    if (str1 !== str2) {

    trace("Same type, but the strings don't match.");

    }

  3. Save the Flash document and select Control > Test Movie.

 

Converting and concatenating strings

TOP

You can use the toString() method to convert many objects to strings. Most built-in objects have a toString() method for this purpose:

var n:Number = 0.470;

trace(typeof(n.toString())); // string

When you use the addition (+) operator with a combination of string and nonstring instances, you don't need to use the toString() method. For details on concatenation, see the second procedure in this section.

The toLowerCase() method and the toUpperCase() method convert alphabetical characters in the string to lowercase and uppercase, respectively. The following example demonstrates how to convert a string from lowercase to uppercase characters.

To convert a string from lowercase to uppercase:

  1. Create a new Flash document and save it as convert.fla.

  2. Type the following code on Frame 1 of the Timeline:

    var myStr:String = "Dr. Bob Roberts, #9.";

    trace(myStr.toLowerCase()); // dr. bob roberts, #9.

    trace(myStr.toUpperCase()); // DR. BOB ROBERTS, #9.

    trace(myStr); // Dr. Bob Roberts, #9.

  3. Save the Flash document and select Control > Test Movie.

NOTE : After these methods are executed, the source string remains unchanged. To transform the source string, use the following:

myStr = myStr.toUpperCase();

When you concatenate strings, you take two strings and join them sequentially into one string. For example, you can use the addition (+) operator to concatenate two strings. The next example shows you how to concatenate two strings.

To concatenate two strings:

  1. Create a new Flash document and save it as concat.fla.

  2. Add the following code to Frame 1 of the Timeline:

    var str1:String = "green";

    var str2:String = str1 + "ish";

    trace(str2); // greenish

    //

    var str3:String = "yellow";

    str3 += "ish";

    trace(str3); // yellowish

    The preceding code shows two methods of concatenating strings. The first method uses the addition (+) operator to join the str1 string with the string "ish". The second method uses the addition and assignment (+=) operator to concatenate the string "ish" with the current value of str3.

  3. Save the Flash document and select Control > Test Movie.

You can also use the concat() method of the String class to concatenate strings. This method is demonstrated in the following example.

To concatenate two strings with the concat() method:

  1. Create a new Flash document and save it as concat2.fla.

  2. Add the following code to Frame 1 of the Timeline:

    var str1:String = "Bonjour";

    var str2:String = "from";

    var str3:String = "Paris";

    var str4:String = str1.concat(" ", str2, " ", str3);

    trace(str4); // Bonjour from Paris

  3. Select Control > Test Movie to test the Flash document.

If you use the addition (+) operator (or the addition and assignment [+=] operator) with a string and a nonstring object, ActionScript automatically converts nonstring objects to strings in order to evaluate the expression. This conversion is demonstrated in the following code example:

var version:String = "Flash Player ";

var rel:Number = 8;

version = version + rel;

trace(version); // Flash Player 8

However, you can use parentheses to force the addition (+) operator to evaluate arithmetically, as demonstrated in the following ActionScript code:

trace("Total: $" + 4.55 + 1.46); // Total: $4.551.46

trace("Total: $" + (4.55 + 1.46)); // Total: $6.01

You can use the split() method to create an array of substrings of a string, which is divided based on a delimiter character. For example, you could segment a comma- or tab-delimited string into multiple strings.

For example, the following code shows how you can split an array into substrings by using the ampersand (&) character as a delimiter.

To create an array of substrings segmented by delimiter:

  1. Create a new Flash document and save it as strsplit.fla.

  2. Add the following ActionScript to Frame 1 of the main Timeline:

    var queryStr:String = "first=joe&last=cheng&title=manager&startDate=3/6/65";

    var params:Array = queryStr.split("&", 2);

    trace(params); // first=joe,last=cheng

    /* params is set to an array with two elements:

    params[0] == "first=joe"

    params[1] == "last=cheng"

    */

  3. Select Control > Test Movie to test the Flash document.

TIP : The second parameter of the split() method defines the maximum size of the array. If you don't want to limit the size of the array created by the split() method, you can omit the second parameter.

TIP : The easiest way to parse a query string (a string delimited with & and = characters) is to use the LoadVars.decode() method, as shown in the following ActionScript:

var queryStr:String = "first=joe&last=cheng&title=manager&startDate=3/6/65";

var my_lv:LoadVars = new LoadVars();

my_lv.decode(queryStr);

trace(my_lv.first); // joe

 

Returning substrings

TOP

 
The substr() and substring() methods of the String class are similar. Both return a substring of a string and both take two parameters. In both methods, the first parameter is the position of the starting character in the given string. However, in the substr() method, the second parameter is the length of the substring to return, and in the substring() method the second parameter is the position of the character at the end of the substring (which is not included in the returned string). This example shows the difference between these two methods:

To find a substring by character position:

  1. Create a new Flash document and save it as substring.fla.
  2. Add the following ActionScript to Frame 1 of the main Timeline:

    var myStr:String = "Hello from Paris, Texas!!!";

    trace(myStr.substr(11,15)); // Paris, Texas!!!

    trace(myStr.substring(11,15)); // Pari

    The first method, substr(), returns a string 15 characters long starting from the eleventh character. The second method, substring(), returns a string four characters long by grabbing all characters between the eleventh and fifteenth index.

  3. Add the following ActionScript below the code added in the preceding step:

    trace(myStr.slice(11, 15)); // Pari

    trace(myStr.slice(-3, -1)); // !!

    trace(myStr.slice(-3, 26)); // !!!

    trace(myStr.slice(-3, myStr.length)); // !!!

    trace(myStr.slice(-8, -3)); // Texas

    The slice() method functions similarly to the substring() method. When given two non-negative integers as parameters, it works exactly the same. However, the slice() method can take negative integers as parameters.

  4. Select Control > Test Movie to test the Flash document.

NOTE : You can combine non-negative and negative integers as the parameters of the slice() method.

You can use the indexOf() and lastIndexOf() methods to locate matching substrings within a string, as shown in the following example.

To find the character position of a matching substring:

  1. Create a new Flash document and save it as indexof.fla.
  2. Add the following ActionScript to Frame 1 of the main Timeline:

    var myStr:String = "The moon, the stars, the sea, the land";

    trace(myStr.indexOf("the")); // 10

    trace(myStr.indexOf("the", 11)); // 21

    The first index of the word the begins at the 10th character because the indexOf() method is case sensitive; therefore the first instance of The isn't considered. You can also specify a second parameter to the indexOf() method to indicate the index position in the string from which to start the search. In the preceding code, Flash searches for the first index of the word the that occurs after the 11th character.

  3. Add the following ActionScript below the code that you added in the previous step:

    trace(myStr.lastIndexOf("the")); // 30

    trace(myStr.lastIndexOf("the", 29)); // 21

    The lastIndexOf() method finds the last occurrence of a substring in the string. For example, instead searching for a character or substring from the beginning of a string, lastIndexOf() starts from the end of a string and works backward. Similarly to the indexOf() method, if you include a second parameter with the lastIndexOf() method, the search is conducted from that index position, although with lastIndexOf() the string is searched backward (from right to left).

  4. Select Control > Test Movie to test your Flash document.

TIP : The indexOf() and lastIndexOf() methods are case sensitive.

 

Copyright ADOBE - All Rights Reserved Worldwide

 

 

More Topics:

Working with Flash Documents

How to work in Flash WorkSpace

Working with Projects in Flash

Process to Build your First Application in Flash

Using Symbols, Instances and Library Assets in Flash

How to Build Video Player in Flash

How to Work with Color, Strokes and Fills in Flash

How to Create Document in Flash

What is Vector and Bitmap Graphics in Flash

How to Create a Banner in Flash, Part 1

How to Work with Text in Flash

How to Create a Banner in Flash, Part 2

How to Use Imported Artwork in Flash

How to Create a Banner in Flash, Part 3

How to Work with Graphic Objects in Flash

How to Work with Layers in Flash

How to Use Filters and Blends

Working with Graphics in Flash

What is Accessibility Features in Flash

How to Create Motion (Shape Tween & Motion Tween) in Flash

How to Create an Application in Flash

What is Masking in Flash

How to Work with Video in Flash

How to Use Layout Tools in Flash

What are Behaviors in Flash

How to Work with Sound in Flash

How to Create Symbols and Instances in Flash

What is ActionScript in Flash

How to Write ActionScript With Script Assist in Flash

How to Add Button Animation and Navigation in Flash

What is Data Integration in Flash

How to Work with Screens

How to Create a Presentation with Screens

What is Extending Flash

How to Create Multilanguage Text in Flash

How to Create Graphics: Draw in Flash

What is Flash Lite

Ways of Data Integration

How to Create Graphics: Create a Timeline Animation in Flash

Getting Started with Flash Lite in Flash

How to Publish Flash Documents

How to Create Graphics: Making Animations with Easing

Learning Flash Lite 1.X ActionScript in Flash

How to Export Flash Content and Images from Flash

How to Create Graphics: Applying Gradients in Flash

Process of Writing and Editing ActionScript 2.0 in Flash

How to Create Accessible Content in Flash

How to Create Graphics: Apply Graphic Filters and Blends

What is Data and Data Types in Flash

Process of Printing from SWF Files in Flash

Using ActionScript: How to Use Script Assist mode in Flash

Learn Syntax and Language Fundamentals in Flash

How to Create E-learning Content in Flash

Using ActionScript: How to Write Scripts in Flash

Working with Functions and Methods in Flash

Process of Using Templates in Flash

Using ActionScript: Process of Adding Interactivity in Flash

What are Classes in Flash

Control Tag Summary of XML to UI in Flash

Using ActionScript: How to Create a Form with Conditional Logic and Send Data in Flash

What is Inheritance in Flash

What is Data Integration: Overview

Using ActionScript: How to Work with Objects and Classes in Flash

Overview on Interfaces in Flash

What is Data Integration: Using XML for a Timesheet

How to Work with Text and Strings in Flash

How to use Handling Events in Flash

What is Data Integration: Using XUpdate to Update the Timesheet

Learning Animation, Filters and Drawings in Flash

How to Work with Movie Clips in Flash

How to Create Interaction with ActionScript in Flash

How to Work with Images, Sound, and Video in Flash

How to Work with External Data in Flash

What is Security in Flash

How to Debug Applications in Flash

List of Error Messages in Flash

Using Object-Oriented Programming with ActionScript 1.0 in Flash

How to Write Scripts for Earlier Versions of Flash Player in Flash

List of all Keyboard Keys and Key Code Values for using in Flash

Terminology

Introduction to Components in Flash

What are Components in Flash

How to Create an Application with Components

How to Work with Components in Flash

How to Handle Component Events in Flash

How to Customize Components in Flash

How to Create Components in Flash

What is Collection Properties in Flash