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 | |||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
About sharing fonts |
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 |
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 |
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 |
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 |
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:
Create a new Flash document and save it as antialiastype.fla.
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.
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.
In the library, right-click the font symbol and select Linkage from the context menu.
The Linkage Properties dialog box appears.
Select the Export for ActionScript and Export in First Frame options, enter the linkage identifier Arial-10, and click OK.
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.
Save your changes to the FLA file.
Select Control > Test Movie to test your Flash document.
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 |
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:
Create a new Flash document and save it as advancedaatable.fla.
Select New Font from the Library panel pop-up menu.
Select Arial from the Font pop-up menu, and then set the font size to 32 points.
Select both the Bold and Italics options.
Enter the font name Arial (embedded) in the Name text box and click OK.
Right-click (Windows) or Control-click (Macintosh) the font symbol in the library, and select Linkage.
In the Linkage Properties dialog box:
Type Arial-embedded in the Identifier text box.
Select Export for ActionScript and Export in First Frame.
Click OK.
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.
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 |
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 |
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:
Create a new Flash document and save it as sharpness.fla.
Select New Font from the pop-up menu in the upper-right corner of the Library panel.
Select Arial from the Font drop-down menu and set the font size to 24 points.
Enter the font name of Arial-24 (embedded) in the Name text box and click OK.
Right-click the font symbol in the library and select Linkage to open the Linkage Properties dialog box.
Set the linkage identifier to Arial-24, select the Export for ActionScript and Export in First Frame check boxes, and click OK.
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.
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 |
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:
Create a new Flash document and save it as gridfittype.fla.
Select New Font from the pop-up menu in the upper-right corner of the Library panel.
Select Arial font from the Font drop-down menu and set the font size to 10 points.
Type the font name Arial-10 (embedded) in the Name text box and click OK.
Right-click the font symbol in the library and select Linkage to open the Linkage Properties dialog box.
Set the linkage identifier to Arial-10, and then select the Export for ActionScript and Export in First Frame check boxes.
Click OK.
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.
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 |
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:
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.
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.
Select Frame 1 on the Timeline and open the Actions panel (Window > Actions).
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;
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);
Select Control > Test Movie to test the application.
Default properties of new text fields |
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 |
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 |
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 |
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 |
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 |
kerning |
kerning |
Recognized values are |
font-style |
fontStyle |
Recognized values are |
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: |
color |
color |
Only hexadecimal color values are supported. Named colors (such as |
Creating a style sheet object |
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 |
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:
In your preferred text or CSS editor, create a new file.
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;
}
Save the CSS file as styles.css.
In Flash, create a new FLA file.
In the Timeline (Window > Timeline), select Layer 1.
Open the Actions panel (Window > Actions).
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.
Save the FLA file to the same directory that contains styles.css.
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 |
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 |
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 |
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:
Create a new Flash document and save it as textareastyle.fla.
Drag a TextArea component from the User Interface folder of the Components panel to the Stage and give it an instance name of myTextArea.
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.
Select Control > Test
Movie to test the Flash document.
Combining styles |
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 |
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 |
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 |
---|---|
|
Affects all |
|
Affects all |
|
Affects all |
|
Affects all |
|
Affects all |
|
Applied to an After the mouse pointer moves off the link, the |
|
Applied to an After the mouse button is released, the |
An example of using styles with HTML |
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:
Create a new file in your preferred text or CSS editor.
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.
Save the file as html_styles.css.
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.
Create a new Flash document in the Flash authoring tool.
Select the first frame in Layer 1 in the Timeline (Window > Timeline).
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.
Save the file as news_html.fla in the same directory that contains the CSS file you created in step 3.
Select Control > Test Movie to see the styles applied to the HTML text automatically.
Using styles to define new tags |
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 |
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:
In Flash, create a FLA file.
Using the Text tool, create a text field approximately 400 pixels wide and 300 pixels high.
Open the Property inspector (Window > Properties > Properties), and select the text field.
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.
On Layer 1 in the Timeline (Window > Timeline), select the first frame.
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.
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.
Save the text file as story.xml.
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.
Save the file as news_xml.fla in the same folder as story.xml.
Run the SWF file (Control > Test Movie) to see the styles automatically applied to the text in the text field.
Using HTML-formatted text |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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:
Create a new Flash document, and save it as tabstops.fla.
In the Timeline, select the first frame on Layer 1.
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.
Select Control > Test Movie to view the formatted table.
Underline tag |
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 |
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 <b> 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 |
---|---|
|
< (less than) |
|
> (greater than) |
|
& (ampersand) |
|
" (double quotes) |
|
' (apostrophe, single quote) |
Flash also supports explicit character codes, such as ' (ampersand - ASCII) and & (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 = "~"; // tilde (ASCII)
my_txt.htmlText += "\t"
my_txt.htmlText += "~"; // tilde (Unicode)
About embedding images, SWF files, and movie clips in text fields |
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 |
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:
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='/adobe-flash-help-tutorials/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.
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='/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.
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 |
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:
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='/adobe-flash-help-tutorials/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).
About specifying height and width values |
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 |
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:
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.
Save the file in the same folder as the animation.fla file you created previously.
this.createTextField("textField_txt", 10, 0, 0, 300, 200);
textField_txt.html = true;
textField_txt.htmlText = "Here's an interesting animation: <img src='/adobe-flash-help-tutorials/animation.swf' id='animation_mc'>";
In this case, the fully qualified path to the newly created movie clip is textField_txt.animation_mc.
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:
stop_btn.onRelease = function() {
textField_txt.animation_mc.stop();
};
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 |
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='/adobe-flash-help-tutorials/home.htm'><img src='/adobe-flash-help-tutorials/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 |
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:
Do one of the following:
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.
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.
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.
Select the Down button on the Stage and type down_btn into the Instance Name text box.
Select the Up button on the Stage and type up_btn into the Instance Name text box.
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;
};
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 |
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.
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 |
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 |
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:
You'll notice that Flash converts the greeting string into IDS_GREETING.
You use these strings when you use the lang_cb combo box to change the language on the Stage.
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.
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 |
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:
Create a new Flash document and save it as ime.fla.
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.
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:
Create a new Flash document and save it as ime2.fla.
Create two button symbol instances on the Stage and give them the instance names enable_btn and disable_btn.
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.
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 |
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 |
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:
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.
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 |
You can use the backslash escape character (\), to define other characters in string literals.
Escape sequence |
Description |
---|---|
|
The backspace character. |
|
The form feed character. |
|
The newline character. |
|
The carriage return. |
|
The tab character. |
|
The Unicode character with the character code specified by the hexidecimal number nnnn. For example, |
|
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 |
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:
Create a new Flash document.
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));
}
Select Control > Test Movie to preview your Flash document. You should see each character traced to the Output panel on a separate line.
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));
}
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:
Create a new Flash document and save it as comparestr.fla.
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.");
}
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:
Create a new Flash document and save it as comparenum.fla.
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.");
}
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:
Create a new Flash document and save it as comparestrict.fla.
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.");
}
Save the Flash document and select Control > Test Movie.
Converting and concatenating strings |
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:
Create a new Flash document and save it as convert.fla.
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.
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:
Create a new Flash document and save it as concat.fla.
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.
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:
Create a new Flash document and save it as concat2.fla.
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
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:
Create a new Flash document and save it as strsplit.fla.
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"
*/
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 |
To find a substring by character position:
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.
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.
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:
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.
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).
TIP : The indexOf() and lastIndexOf() methods are case sensitive.
Copyright © ADOBE - All Rights Reserved Worldwide
More Topics: