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

Beginning ActionScript 2.0 2006

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

Chapter 18

How It Works

In this example HTML was used within a string to define the rich text formatting of the text. System fonts were used, so it was easy to override the font face with Arial on a specific span of text. The face attribute can also refer to the linkage name of a library font if embedFonts is set to true.

Image and SWF Suppor t in HTML Text

Fields

As mentioned earlier, one of the most exciting features of the TextField class is the capability to place image and SWF files within the content of the text field. This allows the text to wrap around images and SWF files for professional-looking layouts.

ActionScript provides properties that enable you to access the SWF within an image tag. You can create pre-loaders, as well as share data and call methods within the SWF file that resides in the text field.

The SWF residing in the image tag has the same security restrictions as external SWF files loaded into the application via loadMovie.

Try It Out

Manipulating an SWF in a Text Field

This is a lengthier example because it requires the creation of two SWF files. The first is the SWF that you’ll load into an image tag. The second defines the text field as well as the HTML that will load the first SWF file. For simplicity, the TextFormat object has been skipped, but you’re welcome to use one as described earlier in this chapter.

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

2.Click anywhere on the stage. The Properties panel populates with options to set for your FLA file. Be sure the Properties tab is selected in the Properties panel and click the Size button. A pop-up window appears. Change the size to 60 width and 70 height and click OK.

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

var titleFormat:TextFormat = new TextFormat(); titleFormat.size = 9;

titleFormat.align = “center”; titleFormat.font = “Arial”;

var dataFormat:TextFormat = new TextFormat(); dataFormat.size = 32;

dataFormat.align = “center”; dataFormat.font = “Arial”;

this.createEmptyMovieClip(“titleHolder”, 0);

var titleField:TextField = this.titleHolder.createTextField(“field1”, ; 0, 0, 50, 60, 20);

titleField.selectable = false; titleField.background = true; titleField.backgroundColor = 0x99CCFF; titleField.text = “Wind Speed”; titleField.setTextFormat(titleFormat);

448

Handling Text

titleHolder.onPress = function()

{

if (this._parent.run)

{

clearInterval(this._parent.run); delete this._parent.run;

}

else

{

this._parent.run = setInterval(this._parent, “changeDisplay”, 10);

}

};

this.createTextField(“field2”, 1, 0, 0, 60, 50); field2.background = true; field2.backgroundColor = 0xECE9E1;

field2.text = “0”; field2.setNewTextFormat(dataFormat);

function changeDisplay()

{

field2.text = 14 + random(3);

}

this.run = setInterval(this, “changeDisplay”, 10);

4.The intricacies of this code aren’t too important, so don’t dwell on that too much. Just know that it simply quickly creates a small interactive SWF file you’ll use in the second half of this exercise.

5.Test the code by selecting Control Test Movie. Click the blue text field to see the animation play and pause. This is the interactive SWF file you embed in a text field. Publish the SWF by selecting File Publish. Be sure the SWF file was published to your workspace folder because you’ll be using a relative link to load the movie into a text field.

6.Open a new FLA file and it as swfinTextTest.fla in your workspace folder (it should be in the same folder as the dataThumbnail.fla and SWF file created in steps 1–5).

7.Highlight the first frame of the swfinTextTest.fla file. 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 = “<p align=’left’>This is some fancy article about weather. It includes a small widget which is supposedly showing real-time data to the reader. Hopefully the reader enjoys it. <img src=’dataThumbnail.swf’ id=’data_mc’/>The happy reader should note that the thumbnail in the text field can be started and paused by pressing the light blue rectangle. Also when you scroll this text field, the SWF will scroll right with it! Astonishing really. You could potentially layout your entire SWF using one text field and simple html, although you might annoy your fellow developers.</p> “;

function watchThumbLoad()

{

var loaded = field1.data_mc.getBytesLoaded();

449

Chapter 18

//Override some ActionScript in the nested clip if (field1.data_mc.run != undefined)

{

clearInterval(watchthumb); clearInterval(field1.data_mc.run); delete field1.data_mc.run;

}

}

watchthumb = setInterval(this, “watchThumbLoad”, 10);

8.Test the code by selecting Control Test Movie.

How It Works

Believe it or not, that’s all there is to it. Setting up a typical HTML field allows the introduction of nested SWF files.

The most notable portion of the code is the watchThumbLoad() function in the second FLA. It watches for a known property of the loaded movie clip. Alternatively, the function could have polled field1.data_mc.getBytesLoaded() and getBytesTotal() to determine the load status of the embedded content.

Once loaded, the watchThumbLoad() function shows how the ActionScript of the embedded SWF is completely accessible as if it were any other movie clip. In this example, the default start state of the SWF file is overridden to allow the user to kick off the activity in it by clicking the light blue rectangle.

In the example you can begin to see how embedding SWF content within a text field can help illustrate your text while encapsulating content directly associated with the text within the text field.

This is, of course, only one approach but it represents a simple and easy-to-manage way to integrate text and visual content in your application.

Font Suppor t

In the examples throughout this chapter, two different methods for using fonts have been described. It is important to note some details about fonts and how you can and should use them in Flash. The difference between device and embedded fonts was described at the beginning of this chapter. This section explores some methods for using fonts in more advanced situations.

Sharing Fonts is probably one of the most useful library sharing options available. By changing out the source SWF containing the font, you can replace the SWF with an SWF that contains a different font, but the same identifier name, enabling you to easily replace fonts within your user interface skin.

Try It Out

Share Fonts at Runtime

This example is lengthier than usual because it requires you to create two SWF files.

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

450

Handling Text

2.Open the Library. 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 appears.

4.Give the font a logical name and choose the font you’d like to embed.

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

6.Select the Export for Runtime Sharing option. The input field above it becomes enabled.

7.This value defaults to the symbol name. Give it an identifying name by changing it to myFont.

8.At the bottom of the same pop-up window is a URL input field. Because the name of the FLA is fontSource.fla, the final SWF name will be fontSource.swf. Enter fontSource.swf as the value in the URL field.

9.Publish fontSource.fla so that it exists in your workspace folder.

10.Open a new FLA and save it as shareFontTest.fla in your workspace folder.

11.Open the Library for the shareFontTest.fla and select New Font from the Options menu. A pop-up window appears.

12.In the Font drop-down list is the name of the font you embedded in fontSource.fla. It’s easy to spot the font because it has an asterisk next to it. In this example, it’s likely to be Font 1*. Select it and click OK.

13.The font symbol will appear in the library. Click it, open the Options menu, and select Linkage.

14.Select the Import for Runtime Sharing option. In the identifier input field, change the default value to myFont.

15.In the URL input field, enter the name fontSource.fla, the SWF that contains the font with the Identifier name myFont.

16.Open the Options menu again and select New Symbol. Be sure the Movie Clip type is selected. Select the checkbox for Export for ActionScript and click OK.

17.The stage now has the new symbol open and waiting for you to modify it. Select the Text tool from the Tools panel and draw a text field.

18.In the Properties panel, be sure the field type is set to Dynamic Text, and select Font 1* from the font drop-down menu.

19.Type at least one character into the text field.

20.Close the movie clip by selecting Scene 1 from the navigation in the Timeline panel.

21.Select frame 1 and open the Actions panel if it’s not already open. Add the following code:

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

my_format.size = 20;

var id:Number = this.getNextHighestDepth();

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

field1.multiline = true;

451

Chapter 18

field1.antiAliasType = “advanced”; field1.embedFonts = true;

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

22.Test the code by selecting Control Test Movie. You will see that the font you chose in the first FLA, fontSource.fla, shows up in sharedFontTest.swf. Change the selected font in fontSource.fla, republish, and test the sharedFontTest.swf file to see the result.

How It Works

In this example, a fontSource.swf file was created to hold a font symbol made accessible to other SWF files. Here, fontSource.swf is required to reside in the same folder as sharedFontTest.swf, so if you deploy the solution to a web server, you will need to upload both files to the server.

The sharedFontTest file contains a library symbol that is linked to the font symbol in the fontSource file.

Using this method for deploying fonts allows you to more easily re-skin and modify the graphics in your application.

The most important departure in this method for allowing shared fonts is the use of the proxy movie clip symbol, which forces the compiler to realize that the Shared runtime font symbol needs to be exported when the application is compiled. Normally shared fonts only work with text fields created with the Text tool. By creating a proxy movie clip, the font becomes available to ActionScript.

Shared fonts and multiple shared fonts can be tricky to set up. Be patient when debugging. Use the FLAs for this chapter to see details about the symbols to include in each file.

Also, notice that the advanced antiAliasType is available, as are all embedded font options.

Hyperlinks and the ASFunction Method

Often when working with links in HTML text, it is desirable to kick off ActionScript functions within the application rather than to call HTTP links. The ASFunction method facilitates this by residing in the href attribute of the <a> tag in the HTML text of the text field. For example, you can define a function called myFunction() and call it from a link like so:

<a href=”asfunction:myFunction”>Some text</a>

The function you specify must belong to the same timeline or object as the text field. You cannot specify dot syntax to traverse the object hierarchy. However, your function can access another function within any timeline.

You can specify only a single String parameter to send to the function, although you can specify multiple strings by using some delimiter such as a comma or pipe. For example, where myFunction() accepts a String parameter, the parameter is defined in the HTML attribute as

452

Handling Text

<a href=”asfunction:myFunction, Test parameter”>Some text</a>

The next Try It Out exercise shows you how to make use of ASFunction-based hyperlinks.

Try It Out

Call ASFunction from HTML

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

2.Highlight the first frame, open the Actions panel, and enter the following code, which defines a background color and a method for changing the color:

import flash.display.BitmapData;

var backgroundColor:BitmapData = new BitmapData (Stage.width, Stage.height, ; false, 0xFFCCCCCC);

this.attachBitmap(backgroundColor, -9999); function changeColor (n)

{

trace(n); backgroundColor.floodFill(2, 2, n);

}

3.Add the following code below the code you entered in step 2:

var myField = this.createTextField(“field1”, this.getNextHighestDepth(), ; 10, 10, 100, 22);

myField.html = true;

myField.autoSize = true;

myField.htmlText = “<a href=’asfunction:changeColor,0x000000FF’><u>Change ; Color</u></a>”;

4.Test the code by selecting Control Test Movie. The text is clickable, and when it’s clicked, the background of the movie changes to blue.

How It Works

In this exercise, you used a simple bitmap to define an object to manipulate using ASFunction within HTML text. A parameter was sent to the receiving function that defined the color to be used.

Using Cascading Style Sheets

One of the most powerful classes in Flash is StyleSheet, available to Flash 7 and up. The StyleSheet class is owned by the TextField class. To most Flash developers, the StyleSheet class is still a mystery and is little used.

By using CSS to define the rich text in your application, you are allowing the application to be more easily maintained, changed, and modified. Flash CSS is quite robust. You can often use the same CSS file or CSS variant file as you use for the rest of your HTML site. When you change the CSS for the HTML page, the text styles in the Flash movie are changed as well.

When creating code for rich text objects, deploying CSS can make your code easier to copy and paste into more applications because the styles are defined in external CSS files rather than intrinsic to the code you’ve written.

453

Chapter 18

Creating a Cascading Style Sheet Object

Creating a StyleSheet object is very simple and uses a typical constructor. For example, the following code creates a StyleSheet called myStyle:

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

You can then load a style sheet from an external source or you can define the styles within ActionScript.

Associating a StyleSheet with a Text Field

Associating a StyleSheet object to a specific text field is easy. The TextField class has a property called

styleSheet that accepts a StyleSheet instance and applies all the styles defined within to the text field. Where there is a text field named myField and a StyleSheet object named myStyle, you associate the StyleSheet only after it has loaded. Loading and detecting onLoad events with style sheets are covered in the following Try It Out.

Try It Out

Use CSS in a Simple Text Field

1.Open a new document in your favorite CSS editor, and enter the following style definitions:

.blogPostText { font-family: Verdana;

font-size: 12px;

}

2.Save the file as myStyle.css in your workspace folder.

3.Open a new FLA and save it as cssTest.fla.

4.Highlight the first frame in the timeline, open the Actions panel, and enter the following:

var id:Number = this.getNextHighestDepth();

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

field1.multiline = true; field1.html = true;

var myStylesheet:TextField.StyleSheet = new TextField.StyleSheet(); myStylesheet.onLoad = function(success)

{

if (success)

{

for (var i in myStylesheet)

{

field1.styleSheet = this;

}

}

field1.htmlText = “<p class=’blogPostText’>The quick brown fox jumped over ; the lazy dog.</p>”;

};

myStylesheet.load(“myStyle.css”);

5.Test the code by selecting Control Test Movie.

454

Handling Text

How It Works

This example demonstrates how to associate a CSS file with a text field. The main drawback to CSS is the time it takes to load the CSS file. Generally, CSS files should remain small to keep response times short.

If you are dealing with a large CSS file, you can alternatively load the file instead with the onData event handler from a LoadVars object. With this technique, you can more accurately watch the bytes being loaded and give the user an indication of why the delay is occurring. When the load is complete, you pass the data from the onData event handler to the parseCSS() method of a StyleSheet object to convert the raw string data into the native data format used by the StyleSheet class. You give this a try in the next Try It Out exercise.

Try It Out

Load CSS via the LoadVars Class

If you have not completed the previous Try It Out example, you should do so now. You’ll use cssTest.fla to make modifications and load the CSS via a LoadVars object.

1.Open cssTest.fla. Open the ActionScript for frame 1 in the Actions panel and remove the load() method from the myStylesheet object because you won’t need it.

2.Add the following code below the code left after following step 1:

var cssProxyLoader:LoadVars = new LoadVars(); cssProxyLoader.onData = function(str)

{

myStylesheet.onLoad(myStylesheet.parseCSS(str));

clearInterval(cssloadWatch);

};

this.watchCSSLoad = function()

{

trace(cssProxyLoader.getBytesTotal());

};

cssloadWatch = setInterval(this, “watchCSSLoad”, 10); cssProxyLoader.load(“myStyle.css”);

3.Test the code by selecting Control Test Movie. The output window will show the bytes loaded, and the text will appear with the style applied.

How It Works

This method for loading CSS data can be helpful when loading large CSS files. It also gives you more options for dealing with the external CSS file because the complete method set for LoadVars is now available to the object.

The most significant line of code is when cssProxyLoader calls the myStylesheet.onLoad method:

myStylesheet.onLoad(myStylesheet.parseCSS(str));

The parseCSS() method of the StyleSheet class does not fire the onLoad event automatically as you might expect. It simply returns a Boolean, so you can call the method directly within the parameter when calling the onLoad event of the target StyleSheet object.

455

Chapter 18

Define Styles Directly on a StyleSheet Object

Styles can be defined directly upon a StyleSheet object using ActionScript rather than loading the styles from an external file. This is useful when you want to encapsulate the text styles within your application but would like to take advantage of StyleSheet capabilities such as hover states and node name definitions. To define your own styles using ActionScript, use the setStyle() method from the StyleSheet class. This method expects two parameters: the name of the style and an object containing propertyvalue pairs for each style attribute.

The name argument to the setStyle() method accepts the same strings that normally represent a style name within a CSS file. You can specify tag names by entering the name of the tag you want to style in quotes, such as “a”, “p”, and “span”. In addition to applying styles to tags of a certain name, you can create your own classes by putting a dot in front of the style name and referring to the style name using the class attribute within one or more tags, as you see shortly. You can also use link selectors to define the appearance of a hyperlink in the link, hover, and active states through the names “a:link”, “a:hover”, and “a:active”. You see these selectors in action in the next Try It Out. Here’s a list of supported selectors:

<a>

<font>

<u>

<i>

<img>

<body>

<b>

<span>

<li>

<br>

<p>

<textformat>

When you put together a list of style properties and their values, you need to know which properties are available to use. The following table lists the style properties supported by Flash, which is a subset of the full CSS1 specification. Because dashes are not allowed in variable names (because a dash is treated as a subtraction symbol), style names with a dash are modified to remove the dash and capitalize the second word.

CSS1 Property Name

Flash Property Equivalent

 

 

color

color

font-style

fontStyle

text-decoration

textDecoration

margin-left

marginLeft

margin-right

marginRight

font-weight

fontWeight

Text-align

textAlign

kerning

kerning

font-size

fontSize

letterSpacing

letterSpacing

text-indent

textIndent

font-family

fontFamily

456

Handling Text

The following example shows how setStyle() is used to apply styles to a text field:

var titleCSS = new TextField.StyleSheet(); titleCSS.setStyle(“.title”, {color:”#660000”, fontSize:”20px”}); titleTextField.styleSheet = titleCSS;

titleTextField.htmlText = “<span class=\”title\”>The Quick</span><br>The quick ; brown fox jumped.”;

The next Try It Out example shows you how to apply styles to a text field.

Try It Out

Define a Style Directly upon a StyleSheet Object

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

2.Highlight the first frame, open the Actions panel, and enter the following code:

var myStylesheet:TextField.StyleSheet = new TextField.StyleSheet(); myStylesheet.setStyle(“a:link”, {

color:”#990000”,

fontSize:”12px”, textDecoration: “underline”

}); myStylesheet.setStyle(“a:hover”, {

color:”#FF0000”,

fontSize:”12px”, textDecoration: “underline”

});

var id:Number = this.getNextHighestDepth();

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

field1.multiline = true; field1.html = true; field1.styleSheet = myStylesheet;

field1.htmlText = “<a href=’www.someurl.com’>This is a link with a hover state!</a> This is some more text, just to see how it looks.”;

3.Test the code by selecting Control Test Movie.

How It Works

In this example you used ActionScript to manipulate the CSS object runtime.

Notice that the setStyle method’s first parameter is a String. This is the class, classpath of the style being defined. The second parameter is an object. An object is always wrapped in curly braces when defined in such a manner. Alternatively, the second parameter could have been defined as a separate object as follows:

var style1:Object = {}; style1.color = “#990000”; style1.fontSize = “12”; style1.textDecoration = “underline”;

var myStylesheet:TextField.StyleSheet = new TextField.StyleSheet(); myStylesheet.setStyle(“a:link”, style1);

delete style1;

457