Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
104
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 18

6.Select the Export for ActionScript option. The input fields above become enabled.

7.Give the font an identifying name. This value defaults to the symbol name. Change it to myFont and click OK. The font will now be added to the SWF file when it is published.

8.Select the first frame in the timeline.

9.Open the Actions panel and add the following code to frame 1:

var my_format:TextFormat = new TextFormat(); my_format.font = “myFont”;

my_format.size = 12;

var id:Number = this.getNextHighestDepth();

var field1:TextField = this.createTextField (“field” + id, id, 10, 10, 300, 100); field1.wordWrap = true;

field1.multiline = true;

field1.text = ‘antiAliasType = “normal”’; field1.embedFonts = true; field1.setTextFormat(my_format);

10.Test the code by selecting Control Test Movie. The text appears. Notice that the text is jagged and difficult to read.

11.Close the SWF and return to the code in the Actions panel. Enter the following code below the code you added in step 9:

id = this.getNextHighestDepth();

var field2:TextField = this.createTextField(“field” + id, id, 10, 40, 300, 10); field2.antiAliasType = “advanced”;

field2.wordWrap = true;

field2.multiline = true;

field2.text = ‘antiAliasType = “advanced”’; field2.embedFonts = true; field2.setTextFormat(my_format);

12.Test the code by selecting Control Test Movie. The text appears. Notice the difference in legibility between the two text fields.

How It Works

In this example, a simple change to the antiAliasType property changed the way Flash rendered the font. The advanced antiAliasType value requires that the font used reside in the library and be accessible via the TextFormat class.

Try a few different fonts. Try changing the pixel size specified in the TextFormat class.

In the next Try It Out, you see the effect of applying the sharpness and thickness properties to control the appearance of text fields when the antiAliasType property is set to advanced.

Try It Out

Using Anti-Aliasing to Improve Text Readability

This exercise uses the FLA file created in the preceding Try It Out. If you have not completed that project, you should do so now.

438

Handling Text

1.Open antiAliasTest.fla in your workspace folder.

2.Open the Actions panel. Enter the following code below the code added in step 11 in the preceding Try It Out:

field1.sharpness = 400;

field1.thickness = 200;

3.Test the code by selecting Control Test Movie. Notice the text with the antiAliasType property set to advanced now looks overly filtered. Artifacts of the process exist that cause the font to look raw and jagged. The values, 400 and 200, are the maximum values allowed.

4.Reduce the values in the two properties you added in step 2. You can go as low as -400 and -200, respectively. Try the following values:

field1.sharpness = 0;

field1.thickness = 150;

5.Test the code by selecting Control Test Movie. Notice how the text appears stronger than the settings specified in step 2, but with the sharpness at zero, it is now smoother.

6.Try different values and view the results. Choose values to suit.

How It Works

In this example, you saw how the two properties sharpness and thickness can be used to manipulate the way in which the text is aliased.

Because aliasing this way makes greater use of your computer’s CPU, you should consider what you will be using the text for. If the text is used for animation, you probably want to avoid high-quality sharpness and thickness values.

The aliasing really works only on fonts sized between 6 and 20 and is best applied to fonts sized 8 to 12. You can try other sizes, but you probably won’t see much change. Advanced aliasing probably isn’t the best idea when tweening text because it does add to the process load.

Rich Text Formatting Options

Most developers are familiar with rich text formatting in relation to HTML. Flash presents several methods for displaying rich text. Each option has limitations and advantages. Generally, the content you expect will drive the decision for which method to use within your application. For example TextFormat is fast and simple, whereas HTML allows for the embedding of images and Flash content within the text field.

Using TextFormat

TextFormat is a class that holds a list of properties capable of defining the look of text within a text field. You can use it to set such things as bold, italics, font, size, and more. You can define these properties in an external file or within the code. One advantage of using TextFormat rather than text properties defined using the Text tool in the Tools panel is that the format is centralized, meaning that if a change

439

Chapter 18

in font or size is required application wide, you can change one object and have the changes propagate through your application.

A TextFormat object is very simple to create, requiring only a minimal constructor:

var titleFormat:TextFormat = new TextFormat();

Properties to define within the object are simply a set of setters. For example, this sets the font to Arial:

titleFormat.font = “Arial”;

The TextField class owns a method named setTextFormat(). The format can be assigned to a specific substring as follows:

titleField.setTextFormat(firstIndex, secondIndex, titleFormat);

If you want to set the format to the entire field, use only one parameter:

titleField.setTextFormat(titleFormat);

You can also copy the format of an existing text field directly onto another by using the getTextFormat() method as follows:

titleField.setTextFormat(appTitleField.getTextFormat());

This enables you to easily propagate a format that is changed dynamically as the application runs.

TextFormat properties can be set and changed anytime, but replacing the contents of the text within the field can cause the field to lose all the properties set using the TextFormat class. In that case, reapply the properties after changing the text field contents by calling setTextFormat() again, referring to the same TextFormat instance as was initially applied to that text field.

Using the code hints within the Actions panel, you can view the full set of properties available.

New Text Format Options for Flash 8

Flash 8 has several new format options, namely justification, letter spacing, and kerning. These new properties affect the spacing and layout of the text within the text field.

Justification

The TextFormat class contains a property called align that determines how the text is placed within the text field. The available values are left, center, right, and justify. While the first three values have been around for a while, the justify option is new to Flash 8. Justified text means that lines that do not reach all the way across the text field are stretched so that all the lines form a clean right margin.

The align property can be applied to fields that use device or embedded fonts.

letterSpacing

The letterSpacing property defines the space that follows a letter. The value is in pixels and can range from -60 to 60. A negative value can result in the letters overlapping, depending upon the font. This

440

Handling Text

property can help the readability of some fonts and can repair the letter spacing on embedded fonts such as English or Cursive that must have no spacing to connect letters properly.

letterSpacing can be used with device or embedded fonts. When using device fonts, an integer must be given. When using embedded fonts, a decimal value such as 3.25 can be specified.

Kerning

Whereas letter spacing affects the spacing between each pair of letters uniformly, kerning allows spacing between letters to be adjusted according to specific combinations of letters and often makes a line of text cleaner.

Auto kerning requires that the font be embedded. The Flash IDE takes into account the kerning information — which pairs of letters should have their spacing adjusted and by how much — which is embedded within the font file itself. The kerning method is only supported when authoring on a Windows PC, but the effect in the final SWF file is visible on the Macintosh as well.

Some fonts, such as Courier New, are monospaced and as such, auto kerning the font has no visible effect.

Try It Out

Associating a TextFormat Object to a Text Field

If you completed the examples earlier in this chapter you’ve seen the TextFormat class in action. In this exercise, the TextFormat class is expanded to use many more properties to control rich text formatting. Using the TextFormat properties is the quickest way to become familiar with them and understand which ones concern you and your design style the most.

This example uses a library font with a linkage name of myFont. If you don’t know how to do this, follow steps 2–8 in the first Try It Out section in this chapter. Alternatively, you can disable the font by removing the font declaration in the my_format object as well as the embedFonts setter of the field1 object.

1.Open a new FLA and save it as setFormatProperties.fla.

2.Highlight frame 1 and open the Actions panel. Add the following code to frame 1’s ActionScript:

var my_format:TextFormat = new TextFormat(); my_format.font = “myFont”;

my_format.size = 12; my_format.align = “justify”; my_format.blockIndent = 10; my_format.italic = true; my_format.bold = true; my_format.bullet = true; my_format.color = 0x666666;

var test:Object = (my_format.getTextExtent(“The quick and the “)); for( var i in test)

{

trace(i+” “+test[i]);

}

my_format.indent = 5; my_format.kerning = true; my_format.leading = 12;

441

Chapter 18

my_format.leftMargin = 10; my_format.rightMargin = 10; my_format.tabStops = [75]; my_format.letterSpacing = 5; my_format.target = “_blank”; my_format.underline = true;

my_format.url = “http://www.twelvestone.com”;

3.The code in step 2 uses all properties of the TextFormat class to make extensive changes to the text style within the text field. Test the code by selecting Control Test Movie. A peculiar thing happens. Although you have not applied the TextFormat to any text fields, the getTextExtent() method returns a value! See the following “How It Works” section for details.

4.Close the SWF and return to the FLA. Add the following code to frame 1, below the code you added in step 2:

var id:Number = this.getNextHighestDepth();

var field1:TextField = this.createTextField(“field” + id, id, 20, 20, 300, 150); field1.html = true;

field1._target field1.selectable = false; field1.border = true; field1.wordWrap = true; field1.multiline = true;

field1.antiAliasType = “advanced”;

field1.embedFonts = true;

field1.text = “The quick brown fox jumped over the lazy dog. “; field1.text += “The quick\t brown fox jumped over the lazy dog.+newline “; field1.text += “The quick brown fox jumped over the lazy dog. “; field1.text += “The quick brown fox jumped over the lazy dog. “; field1.text += “The quick brown fox jumped over the lazy dog. “; field1.text += “The quick brown fox jumped over the lazy dog. “; field1.text += “The quick brown fox jumped over the lazy dog. “; field1.setTextFormat (my_format);

5.Test the code by selecting Control Test Movie. You’ll now see that a text field appears in the stage with some rather intrusive style changes.

6.Close the SWF and return to the FLA. Return to the first frame ActionScript and change some or all of the values in the my_format object. Test the code with each change by selecting Control Test Movie and note the changes in the text appearance.

How It Works

In this example you used every TextFormat property available in Flash 8. There were a few dependencies. For example, although you aren’t using HTML text, the format object included a URL value. To enable the URL value and make the field clickable, the field1.html property was set to true. The embed font option was also required because the TextFormat object called for kerning.

The bullet property adds a bullet at the beginning of the text and wherever a newline character is encountered. This method enables you to easily create a bulleted list within a text field.

The TextFormat class’s getTextExtent() method is capable of helping you predict the size and position of text before it’s ever rendered on the stage. The method takes into account the properties set thus

442

Handling Text

far upon a TextFormat object. The results of the method showed up in the Output window when the code was tested using Control Test Movie. The results can be used to help determine the size of user interface objects before they are ever built nd to help you measure text without having to instantiate a text field offstage and measure the field, as was required in previous versions of Flash.

Italic and bold are generally used with device fonts. A text field can only use the characters embedded with a font when embedFonts is set to true. If the library font is italic but not bold, setting bold to true does nothing as long as the embedded font doesn’t include bold characters. However, when using device fonts, Flash can request the bold and italic sets from the operating system, and the change becomes visible.

Tab stops are characters represented by the special code \t, which represents the ASCII tab stop character. Each tab stop is defined by an index and is relative in size. In this case, the first tab in the text takes on the tab width of 75 pixels.

The rest of the properties are straightforward, and changing the values of each property and viewing the result will enable you to quickly become familiar with each property.

Now learn to use properties to apply formatting to substrings.

Try It Out

Applying a TextFormat Property to Substrings

1.Open a new a FLA and save it as setFormatSpan.fla.

2.Open the Library panel. At the top right is an icon that looks like a bulleted list with a small arrow pointing down. Click it to open the Options menu.

3.Select the New Font option. A pop-up window opens.

4.Give the font a logical name and choose the font you’d like to use in your text field as advanced rendered font. Click OK.

5.The font appears in the Library. Click the font symbol in the library so that it is highlighted. Open the Options menu again, and select the Linkage option. A pop-up window with options appears.

6.Select the Export for ActionScript option. The input fields above it become enabled.

7.Give the font an identifying name. The value defaults to the symbol name. Change it to myFont and click OK. The font will now be added to the SWF file when it is published.

8.Highlight the first frame and open the Actions panel. Add the following code to frame 1:

var my_format:TextFormat = new TextFormat(); my_format.font = “myFont”;

my_format.size = 12;

var id:Number = this.getNextHighestDepth();

var field1:TextField = this.createTextField (“field” + id, id, 20, 20, 300, 150);

field1.border = true; field1.wordWrap = true; field1.multiline = true; field1.antiAliasType = “advanced”; field1.embedFonts = true;

field1.text = “The quick brown fox jumped over the lazy dog. “;

443

Chapter 18

field1.text += “The quick brown fox jumped over the lazy dog. “; field1.text += “The quick brown fox jumped over the lazy dog. “; field1.text += “The quick brown fox jumped over the lazy dog. “; field1.text += “The quick brown fox jumped over the lazy dog. “; field1.text += “The quick brown fox jumped over the lazy dog. “; field1.text += “The quick brown fox jumped over the lazy dog. “; field1.setTextFormat (my_format);

9.Test the code to be sure you have a working text field before proceeding. It would be difficult to debug the rest of the code if this isn’t working yet. Select Control Test Movie. You should see a small text field with repeating text within it, using the font you specified in the library.

10.Close the SWF and return to frame 1’s ActionScript. Define a TextFormat object to apply to specific substrings within the text in the text field. Enter the following code below the code you added in step 8:

var keywordHighlight:TextFormat = new TextFormat(); keywordHighlight.bold = true;

keywordHighlight.color = 0xFF0000; keywordHighlight.size = 13;

11.Now that you have a format, create a function that is capable of looking for and applying a format to a specific substring throughout the text. Enter the following function below the code you added in step 10:

function setHighlights (field, format, subStr)

{

var str:Array = field.text.split (subStr); var tempString:String = “”;

for (var i = 0; i < str.length; i++)

{

tempString += str[i];

var startPos = tempString.length; tempString += subStr;

field.setTextFormat(startPos, startPos + subStr.length, format);

}

}

12.The code added in step 11 might look a bit confusing; it is explained in the following “How It Works” section. For now, assume this function automates the searching of a substring and allows you to easily apply a format to specific substrings using a simple line of code. Add the following line below the code you added in step 11:

setHighlights(field1, keywordHighlight, “fox jumped”);

13.Test the code by selecting Control Test Movie. You should see the substring “fox jumped” is now red, bold, and slightly larger than the surrounding text.

How It Works

In this exercise you took advantage of the setTextFormat() method’s capability to accept string positions to apply a format to spans of text rather than an entire field.

444

Handling Text

In the setHighlights() function, the field’s text is split using the split method, creating an array of characters in the variable str. (Splitting the string into an array makes it easier to find substrings in this case.)

Once the text is split, a temporary string object called tempString is created. This variable enables you to easily measure the beginning position of each substring without affecting the text already in the text field. The start position is identified as the length of the tempString variable each time the loop is run.

With each loop the tempString variable grows and thus the entire length of the tempString variable is the new start position of the span you want to format. The start position is defined as startPos using the length property of tempString as it is built. Once the measurement is taken, the substring is added to the text so that the next function run displays an accurate length of text processed thus far in the current loop iteration.

Finally, and most importantly, the setTextFormat() method is used on the actual text. The startPos variable is assigned as the start value of the span that will have the format applied. This is the first parameter in the line:

field.setTextFormat(startPos, startPos + subStr.length, format);

Because you only want to highlight the substring, you then set the end position of the span to be the length of the substring. This value is assigned as the start position with the substring length added to it:

field.setTextFormat(startPos, startPos + subStr.length, format);

Finally, the format is defined as the last parameter:

field.setTextFormat(startPos, startPos + subStr.length, format);

Rather than use the setHighlights() function you could have also more literally defined a specific span without regard to a specific substring. For example, you can remove the line you added in step 12 and simply replace it with this line:

field1.setTextFormat(5,15,keywordHighlight);

In this case you will see how 10 characters (including spaces) are reformatted with the keywordHighlight format. The example, however, shows a practical and useful way that the span parameters of setTextFormat() can be used within an application.

The setTextFormat() method overrides only those styles defined in the new style. So if the original style uses an underline, and your new style does not indicate an underline either true or false, the underline will remain.

A Note about setNewTextFormat()

When you add text to a text field that is not HTML enabled, the text defaults to the format assigned to the field at author time. So if you add a text field to the stage using the Text tool, any new text added by the user or with ActionScript will take on the rich text formatting the field is published with.

445

Chapter 18

If you don’t set any default format or use the createTextField() method as shown in the examples in this chapter, Flash defaults to black, Serif, and 12. It is possible to change the default style of the field on-the-fly by using setNewTextFormat() instead of setTextFormat(). When you use setNewTextFormat(), it not only applies the format to the text, but also makes it the text field’s default style. This can be handy when working with input text, or dynamic text to which a user might apply rich text formatting options. If a text field is going to use only one style throughout its lifetime, and the text is destined to change multiple times, use setNewTextFormat() to avoid having to recall the setTextFormat() method every time the text changes. You can still override the default style with spans or redefine the style by using setTextFormat(). Use setNewTextFormat() where it makes sense.

Displaying HTML

HTML presents one of the easiest methods for displaying rich text in Flash. Flash cannot open a web page, but it does support a modest array of HTML tags. The tags support the use of style attributes that can be used in conjunction with a style sheet.

The following table identifies supported HTML characters:

Code

Character

&

&

'

>

>

&lt

<

&quote;

In addition, Unicode and ASCII characters can be used to define characters not in the preceding list. For example, @ produces the @ symbol. You can also specify the value as Unicode.

Here’s a list of HTML tags that are supported in Flash:

<a>

<font>

<u>

<i>

<img>

<body>

<b>

<span>

<li>

<br>

<p>

<textformat>

In the following CSS section you see how the style class can expand on the supported tag set and include your own.

The image tag is especially interesting because it allows the embedding of not only images, but SWF files as well.

Because only a rudimentary set of HTML can be used within a text field, you cannot load a web site into a text field and expect it to display. Most, if not all, simple XHTML pages should work to some degree, as long as you use CSS and style tags appropriate for the styles available in Flash. For example, it won’t do any good to set a border for a <span> tag.

446

Handling Text

Enabling HTML in a text field is very easy. The TextField class has a property called html. When it’s set to true, the text field enables HTML parsing on the field. For example:

contentField.html = true;

That’s literally all you need to do to your text field.

One extra step is to be sure the text is set with the proper setter. In most cases the property text is used. For example:

contentField.text = “Some string of information.”;

And:

contentField.text = “<b>Some string of information.</b>”;

In both cases, whether or not HTML is set to true, the text field will not render the text as HTML. The property htmlText must be used to allow the text field to parse the string as HTML. For example:

contentField.htmlText = “<b>Some string of information.</b>”;

In this case the string displays as bold as long as the html property is set to true. If the html property is not set to true, the text field displays the text as if the text setter had been called.

This next Try It Out example is short and simple and shows you how to apply HTML to a text field. If you are interested in adding more HTML tags, try them on your own to see how each behaves in Flash. The tags are more thoroughly covered in the “Using CSS with XML” at the end of this chapter because that’s where HTML text really begins to show its power within Flash.

Try It Out

Creating and Displaying HTML Text

In this exercise you apply HTML to a text field.

1.Open a new FLA and save it as htmlInFlash.fla in your workspace folder.

2.Select frame 1 to highlight it. Open the Actions panel and enter the following code:

var id:Number = this.getNextHighestDepth();

var field1:TextField = this.createTextField(“field” + id, id, 20, 20, 300, 150); field1.html = true;

field1.border = true;

field1.wordWrap = true; field1.multiline = true;

field1.htmlText = “<font face=’Arial’>The <i>quick</i></font> brown fox <b>jumped</b> over the lazy dog.</font> “;

3.Test the code by selecting Control Test Movie. You’ll see a text field with text variously styled throughout the string.

4.Try changing the HTML tags by adding size and color attributes to the font tag, or change the italic and bold tags. Try inserting <p> tags to define specific paragraphs of text. Test the code with each change to see what each change does to the text.

447