Movie-Related Classes and Global Objects

   

Movie- Related Classes and Global Objects

graphics/new_icon.jpg

ActionScript defines a number of classes and global objects (singletons) designed specifically for creating Web animation. Sixteen such classes are categorized as Movie-related and listed under Built-in Classes, Movie in the Macromedia Flash MX Toolbox list (on the left side of the Actions panel). These 15 Movie objects are as follows : Accessibility , Button , Color , ContextMenu , Key , LocalConnection , Mouse , MovieClip , PrintJob , Selection , Sound , Stage , TextField , TextFormat and TextSnapShot. Three of these, ContextMenu , PrintJob and TextSnapShot , are new in Flash MX 2004.


These Flash-specific objects are not defined in the ECMA-262 standard or implemented in JavaScript. Nevertheless, they include some of the most widely used classes in ActionScript, such as MovieClip , TextField , and TextFormat .

All the movie-related classes and objects are listed in Table 21.11.

Table 21.11. Movie-Related Objects

Object

Represents

Singleton?

Comments

Accessibility

Screen reader program

Y

 

Button ( [n] )

Onscreen buttons

N

( [*] )

Color

Colors

N

 

ContextMenu

Flash Player context menu

N

( [n] )

Key

Keystrokes

Y

 

LocalConnection

Local inter-movie communication

N

 

Mouse

Mouse cursor and clicks

Y

 

MovieClip

Movie clip

N

( [*] )

PrintJob

Printing

N

( [n] )

Selection

Edit text selection and focus

Y

 

Sound

Sound/music

N

 

Stage ( [n] )

The Stage

Y

 

TextField

Text fields

N

 

TextFormat

Formatting for text in text field

N

 

TextSnapShot

Static text

N

( [n] )


[n] new in Flash MX 2004

[*] not a singleton, but can't create new instances with new keyword

The Accessibility Object

graphics/new_icon.jpg

The Accessibility object represents the ability of the Flash Player to make Flash movies accessible to the visually impaired. Flash accessibility relies on screen reader software that supports Microsoft Active Accessibility (MSAA). Screen reader software interprets text and certain other screen elements and reads them out loud. Window-Eyes from GW Micro is currently the most popular screen reader that supports Active Accessibility.


The Accessibility object has two documented properties:

The isActive() method checks whether an MSAA-compliant screen reader is active. Based on this information, you can load a more accessible interface into your movie or steer the user to a special accessible site. You should wait a second or two after your movie has loaded before executing isActive() . Otherwise, you may get a false return, even though a screen reader is active.

graphics/new_icon.jpg

You use the updateProperties() method after you have changed an accessibility property. The updateProperties() method causes Flash Player to update its description of all accessible objects and notify screen readers of any changes.


graphics/new_icon.jpg

There is also an _accProps variable, which can be used as a global variable applying to the whole movie, or as an attribute of a movie clip, button, dynamic text field, or input text field. It lets you set accessibility options, overriding those set in the Accessibility Panel at authoring time.


There are five accessibility properties. Three of them, name , description , and shortcut (keyboard shortcut) are self-explanatory. The other two are as follows:

  • silent Whether the movie or object "talks"that is, whether it has been made accessible; true means it is not accessible.

  • forceSimple Whether child movies or objects are accessible; true means they are not accessible.

You can use the System.capabilities.hasAccessibility property to determine whether the system supports MSAA (even though the reader may not be currently active).

For more information on accessibility, see http://www.macromedia.com/macromedia/accessibility/features/flash/ and Appendix B, "Making Flash Accessible," page 977 .


The Button Class

The Button class has five properties ( enabled , tabEnabled , tabIndex , trackAsMenu , and useHandCursor ) and nine dynamic events ( onPress , onRelease , onReleaseOutside , onRollOver , onRollOut , onDragOut , onDragOver , onKillFocus , and onSetFocus ).

Button events are covered in "Button Events," page 508 , in Chapter 20. The Button properties are the same as those for movie clips, described in the table of movie clip properties in Appendix A, "ActionScript Reference."


The Button class has only one method, getDepth() , which returns the depth of the button instance.

The Button constructor function cannot create new buttons. You have to create buttons manually or by using attachMovie() . (However, the initObject argument of attachMovie() does not work with buttons. )

The Color Class

Each instance of the Color class programmatically controls the color and transparency (alpha) of a particular movie clip or of the main movie. You can use color changes to simulate various conditions. For instance, continuously darken the color of an entire movie to simulate nightfall, or add yellow and white when a spotlight hits something. Alpha can be used for fade-ins and fade-outs, and to simulate something semi-transparent like a veil.

In Flash, color has four components : red, green, blue, and alpha (or transparency).

You can work with color in ActionScript in two basic ways:

  • Set or get a new color, replacing any existing color and not affecting alpha. To do so, use the setRGB() and getRGB() methods .

  • Use setTransform() to modify an existing color, or use getTransform() to determine how the color is currently transformed. Using the transform approach, you can set and get alpha in addition to color.

Either way, you first need to create a color object for a particular movie clip, by using the target movie clip's instance name as the single string parameter to the new statement:

 myColor = new Color("myClip"); 

setRGB() and getRGB()

You can set the color of a movie clip using setRGB() and a six-digit hexadecimal number representing three pairs of digits. The pairs represent red, green, and blue values, respectively. Here are some examples:

 myColor.setRGB(0xFF0000); // sets myColor to red myColor.setRGB(0x00FF00); // sets myColor to green myColor.setRGB(0x0000FF); // sets myColor to blue 

For more details on hexadecimal notation, see hexadecimal.htm on the CD accompanying this book.


Web developers are familiar with hexadecimal numbers from HTML syntax like the following:

 <BODY BGCOLOR="#00FF00"> 

In Flash, the fill-color box (indicated by a Paint Bucket icon in the Colors section of the Toolbox) gives you a handy way to determine the hexadecimal values of colors. Click on the fill-color box and then run the Eyedropper over the color swatches. As the Eyedropper passes over a swatch, the hexadecimal value of the color appears in the input box at the top of the fill-color box.

The getRGB() method returns the currently assigned color. For instance, to compare the colors stored in two instances of the Color class, you can use getRGB() .

The getRGB() method returns the color as a decimal number. To transform that into a hexadecimal number, use the toString() method of the Number class, like this:

 hexColor = myColor.getRGB().toString(16); 

setTransform() and getTransform()

The setTransform() method allows you to transform all the colors and the alpha of a given movie clip. For instance, if you have a movie clip that contains 100 other clips of various colors, you can remove a little red and add a little blue on all of them in one operation by using setTransform() . In contrast, with setRGB() , you can only set them all to the same color. The setTransform() method is most useful for making changes to bitmaps, which contain many colors that you cannot address individually. The setTransform() method allows you to achieve subtle changes in tint exactly the same as those achievable via the Advanced Effect panel. (In the Properties Panel, select Advanced in the Color combo box, and then click the Settings button.)

Before you can use setTransform() and getTransform() , you need to create a transform object , which has eight properties corresponding to the eight input boxes on the Advanced Effect panel.

Both the Advanced Effect panel and the transform object contain four pairs of numbers, corresponding to red, green, blue, and alpha. The first number in each pair, the transformation percentage , is an integer from -100 to 100 , which serves as a percentage multiplier for the existing color. The second number in each pair, the offset , is an integer from -255 to 255 , which represents a color value. You take the result from the percentage multiplication and add the offset color value. Expressed in an equation, it looks like this:

 newColor = ( oldColor x transformationPercentage ) + offset 

This equation is, in fact, shown on each of the four lines in the Advanced Effect panel.

The transformation percentage multipliers are ra , ga , ba , and aa , for red, green, blue, and alpha, respectively.

The offset color values are rb , gb , bb , and ab , for red, green, blue, and alpha, respectively.

The following line of code creates a transform object, using an object literal:

 myTransform = {ra:100,rb:255,ga:100,gb:255,ba:100,gb:255,aa:100,ab:255}; 

After you create a transform object, you can apply it to any instance of the Color class, as follows:

 myColor.setTransform(myTransform); 

The color of the movie clip associated with myColor changes.

Multiple setTransform() operations are not cumulative. Each transform operates on the original color values, assigned at authoring time or using the drawing API.

The getTransform() method returns a copy of the current transform objectthe one set with the most recent setTransform() .

The ContextMenu Class

graphics/new_icon.jpg

Creating the ContextMenu object itself using the customItems attribute (an array of ContextMenuItem objects) is covered in Appendix A, "ActionScript Reference." ContextMenu events are covered in " Using Event Handlers to Trigger Action" in Chapter 20. Also see contextMenu.fla on the CD accompanying this book.


The Key Object

The Key object represents user input via the keyboard.

The Key object has just four methods: getAscii() , getCode() , isDown() , and isToggled() .

For an explanation of the four Key object methods, and for examples of using Key class methods with and without listeners, see "Key Events," in Chapter 20, page 511 . Just preceding the "Key Events" section in Chapter 20, the last item in the "Button Events" section is an explanation of the on(keyPress) button event, page 508 .


Eighteen constants, such as Key.BACKSPACE and Key.TAB , allow you to conveniently refer to commonly used keys without having to use their numeric codes. For instance:

 if (Key.isDown(Key.UP)) {      // then do things } 

For a listing of methods and constants associated with the Key object, see Appendix A, "ActionScript Reference," under "Key Object Methods and Constants."


If you need to determine the keycode of a particular key, you can create a keycode tester with the following code (also included on the CD as keytester.fla):

 _root.createTextField("myTextField", 1, 50, 50, 100, 50); myTextField.variable = "kc"; myTextField.setNewTextFormat(new TextFormat(null,20,0x000000,true)); _root.onEnterFrame = function () {      kc = String.fromCharCode(Key.getCode())+" : "+Key.getCode(); }; 

When you press a key, its numeric code is displayed in the text field.

If you want to test keycodes within the authoring environment, select Control, Disable Keyboard Shortcuts while the movie is running. Disabling keyboard shortcuts allows the preceding code to pick up keys such as Backspace and Tab that are normally "trapped" by the keyboard shortcut feature.

The LocalConnection Class

For more on LocalConnection , see tictactoe.htm, tictactoe_lc.fla, and player_lc.fla on the CD accompanying this book.


The LocalConnection class makes it possible for multiple SWFs running on the same computer to communicate. A movie can trigger an event handler in another movie, and movies can exchange arbitrary data. The local connection feature is browser independent and thus works regardless of JavaScript support in the browser. It also works in the Flash 6 Player and in Flash projectors.

To enable a movie to communicate over a local connection, you must first create an instance of the LocalConnection class. You can use that one instance to communicate over any number of connections or virtual channels. Each connection has its own name and is a one-to-one communication channel with another movie. To send over a connection, you use the send() method of the local connection instance. To receive, you use the connect() method.

The format for the constructor function is straightforward:

 myLocalConnection = new LocalConnection(); 

The LocalConnection class has four methods: send() , connect() , close() , and domain() . You use both send() and connect() whenever you use a local connection, though some SWFs may only send, whereas others may only receive.

In addition, if the communicating movies are not in the same domain, you need to create an allowDomain or allowInsecureDomain handler in the receiving movie to validate domains from which you are willing to receive. You can also define an onStatus event handler in the sending movie, which receives a notification of success or failure when you invoke the send() method. The onStatus event handler is invoked when a send() command returns true . (The send() command returning true indicates that the format of the command was acceptable, but not that the data was actually dispatched.) The onStatus event handler receives as a parameter an object with a string property named level . If the value of the level property is status , the data was dispatched successfully. If the value of the level property is error , the data was not dispatched successfully. This occurs, for instance, if there is no one "listening" on that connection.

The following code, from tictactoe_lc.fla on the CD, displays the connection status in a text field, along with a name identifying the SWF:

 myName = "tictactotallyautomatic"; xLC.onStatus = function(infoObject) {      if (infoObject.level == "error") {           _root.statusField.text = myName+" Connection xLC failed.";      }      else _root.statusField.text = myName+" Connection xLC succeeded."; } 

See Table 21.12 for a listing of LocalConnection methods and event handlers.

Table 21.12. LocalConnection Methods and Event Handlers

Name

Method/Event Handler

Format

Description

send

M

myLocalConnection.send( connectionName, method[, p1 ... pN] )

Sends data over connectionName . Returns true if the format of the command is acceptable.

connect

M

myLocalConnection.connect( connectionName )

Starts listening on connectionName .

close

M

myLocalConnection.close( connectionName )

Removes connection. Returns true if successful, false if no such connection exists.

domain

M

myLocalConnection.domain()

Returns a string containing the name of the domain of the SWF containing the LocalConnection instance. For example, macromedia.com .

allowDomain

E

myLocalConnection.allowDomain = function ( senderDomain ) { }

Created on the receiver, should return true if senderDomain is an acceptable sending domain.

onStatus

E

myLocalConnection.onStatus = function ( infoObject ) { }

Provides notification, via the infoObject .level property, of success or failure of a send() command.


The format for the send() method is as follows:

 myLocalConnection.send(  connectionName, method[, p1  ...  pN]  ) 

Both connectionName and method are strings. The optional parameters supplied as p1 through pN may be of any datatype. The movie that is "listening" on the connection named in connectionName automatically executes the event handler named in method . Parameters p1 through pN are passed to the method.

Here's a send() example, also from tictactoe_lc.fla, using a local connection instance named xLC , a connection named xmove , an event handler named move() , and a variable named num .

 xLC.send("xmove", "move", num); 

On the receiving end, the connect() method is used to associate the event handler method with a particular connection. The format is simple:

 myLocalConnection.connect(  connectionName  ); 

Here's an example that uses a local connection instance named oLC and a connection named xmove :

 oLC.connect("xmove"); 

Receiving movies use the allowDomain() or allowInsecureDomain() method to accept or reject connections, based on the sender's domain. The ActionScript interpreter passes the domain name to the allowDomain() event handler as a parameter. If the allowDomain() method returns true , the connection is allowed. In the following example, only connections from allowedDomain.com are accepted:

 xLC.allowDomain = function(senderDomain){      return (senderDomain == "allowedDomain.com"); } 

Senders and receivers can specify the sender's domain explicitly, as in the following examples:

 xLC.send("flashoop.com:xmove", "move", num); the oLC.connect("flashoop.com:xmove"); 

If the connection name contains a colon , it is assumed that you have provided the domain name explicitly.

If the connection name does not contain a colon, by default it is prefixed with the domain of the movie containing the LocalConnection instance. Thus, two SWFs running in the same domain can use a connection name with no domain name, as in the following examples:

 xLC.send("xmove", "move", num); oLC.connect("xmove"); 

For SWFs loaded from the local hard disk, the domain is localhost . For example, the following two statements are equivalent if the sending movie was loaded from the local hard disk:

 oLC.connect("xmove"); oLC.connect("localhost:xmove") 

When you're loading SWFs from different domains, if you want to accept the connection without checking the domain name, take these two steps:

  • Start the connection name with an underscore character. Messages will be sent with no domain name. Here are examples:

     oLC.connect("_myConnection"); xLC.send("_myConnection", "move", num); 

  • Create an allowDomain() handler for the receiver that always returns true , as in the following example:

     oLC.allowDomain = function(senderDomain){      return true; }; 

Connections whose names begin with an underscore character are also accepted if the actual domain is localhost , even with no allowDomain() method.

There is no built-in multicasting for local connections. Thus, for instance, if three movies must all communicate with one another, each movie uses three connections: one to "listen" on and one to talk to each of the other movies. For instance, one movie might be listening on a connection named incominga , one on incomingb , and one on incomingc . In that case, the relevant code in the first movie would look like this:

 1: myLocalConnection = new LocalConnection(); 2: myLocalConnection.connect("incominga"); 3: myLocalConnection.onReceive = function(message) { 4:      // your event handler code goes here 5: } 6: function sendAll() { 7:      myLocalConnection.send("incomingb", "onReceive", _root.input.text); 8:      myLocalConnection.send("incomingc", "onReceive", _root.input.text); 9: } 

The code in the second movie would look the same, except that it would have incomingb on line 2 and incominga on line 7. The third movie would have incomingc on line 2 and incominga on line 8.

The Mouse Object

graphics/new_icon.jpg

The Mouse object represents user input via the mouse. Flash MX 2004 has added one new event for Windows only, onMouseWheel , to the existing onMouseMove , onMouseDown , and onMouseUp .


For a discussion of Mouse events, see "Mouse Events," page 512 , in Chapter 20. Also see the "Button Events" section, page 508 . Most button events are mouse-related.


Beyond its event-related capabilities, covered in Chapter 20, the Mouse object has two methods: show() and hide() . The hide() method allows you to hide the standard mouse cursor. Then you can substitute a custom mouse cursor. The show() method makes the standard mouse cursor visible again.

For instance, say you want your cursor to look like a magic wand. Create a movie clip containing the magic wand graphic. Then, if the clip's instance name is magicWand , the code looks like this:

 Mouse.hide(); _root.onEnterFrame = function () {       magicWand._x = _root._xmouse       magicWand._y = _root._ymouse } 

Then, to go back to the standard cursor, do this:

 magicWand._visible = false; Mouse.show(); 

The PrintJob Class

graphics/new_icon.jpg

The PrintJob class, new in Flash MX 2004, gives you more control over printing, which has long been a weak point in Flash. Using the PrintJob class is a five-step process:


  1. Create a new PrintJob instance, using the new keyword.

  2. Use the start method to display the operating system Print dialog to the user. If the user cancels or an error occurs, the start method returns false . Otherwise, the user has chosen to print, and the start method returns true .

  3. Use the addPage method one or more times to add pages to the print queue.

  4. Use the send method to initiate printing. This brings up the standard operating system Print dialog, giving the user the opportunity to print or cancel.

  5. Delete the PrintJob instance.

After the user has chosen to print, five attributes are set to show the page setup characteristics the user has chosen. These are shown in Table 21.13. These attributes can only be set automatically; they are "read-only" from your point of view as a programmer.

Table 21.13. Page Setup Attributes

Property

Type

Units

Comments

myPrintJob.paperHeight

Number

Points

Paper height

myPrintJob.paperWidth

Number

Points

Paper width

myPrintJob.pageHeight

Number

Points

Height of printable area (ignores any user-defined margins)

myPrintJob.pageWidth

Number

Points

Width of printable area on the page (ignores any user-defined margins)

myPrintJob.orientation

String

n/a

portrait or landscape


Only the addPage method has any complexity to it, in that it allows you to print just a portion of the screen, just a particular level or frame, to limit printing to a particular movie clip, as well as to use a printAsBitmap option that captures transparency and color effects of bitmaps. (By default Flash prints in a vector mode.)

Here is a minimal addPage method call, which prints level zero, in the default vector mode, including the whole Stage, and not limiting the printing to any particular movie clip:

 myPrintJob.addPage(0); 

Here's as example that limits printing to a particular area of the screen. The numbers are given in pixels, measured from the registration point, which is the upper left for the root and the midpoint for child movie clips. Thus, this will give you an area starting at the upper left and including 500 pixels over to the right and 400 pixels down.

 (myPrintJob.addPage(0, {xMin:0,xMax:500,yMin:0,yMax:400})) 

This adds printing in the bitmap mode, and printing only frame 3 of level 2:

 myPrintJob.addPage(2, {xMin:0,xMax:500,yMin:0,yMax:400}, {printAsBitmap:true}, 3) 

If you want to skip one option, but use a subsequent option, use null for the skipped option. For instance, to print frame 3 but use the default full-screen and vector printing:

 myPrintJob.addPage(0, null, null, 3) 

The addPage method returns true if the call was successful (that is, the page was added to the queue), and false if it was unsuccessful (nothing was added to the queue).

Here's a complete print job session:

 var myPrintJob = new PrintJob(); ok = myPrintJob.start();  // user prints or cancels job if (ok) {     trace ("user chose to print the job");     for (i in myPrintJob) trace (i+" : "+myPrintJob[i]); // show page setup     success = myPrintJob.addPage(0);     if (success) trace ("page added to queue");     myPrintJob.send(); } else trace ("job cancelled") delete myPrintJob; 

The Selection Object

The Selection object controls the edit text selection and focus.

Events for the Selection object are covered in "Selection Events," page 515 , in Chapter 20. For more details on selection and focus, also look in "Event Handlers and Focus," page 507 ; "Button Events," page 508 ; and "Key Events," page 511 .


In addition to its event-based capabilities, the Selection object has three methods dealing with the currently selected text, or selection span . Each of these methods returns an index into the selected text. The index is zero-based . That is, the first position is 0, the second position is 1, and so on.

getBeginIndex() returns the index of the beginning of the selection span.

getEndIndex() returns the index of the end of the selection span.

In both cases, if the method fails to find a valid index (for example, because there is no currently focused selection span), the method returns -1 .

getCaretIndex() returns the index of the blinking cursor position. If no blinking cursor is displayed, the method returns -1 .

For instance, to find out whether the cursor is at the end of a selected text field, you do the following:

 if ( Selection.getCaretIndex() == Selection.getEndIndex() )      // do something 

The Shared Object Class

The Shared Object class creates persistent storage of ActionScript objects on the user's local hard drive. The typical usage of this class is similar to that of "cookies" for browsers, namely, to store user-specific information on the user's computer, in such a way that the user can exit the application and even turn off the computer, without destroying the stored information. The next time the user starts the application, the application is able to access the shared information. For instance, a shared object could be used to store a username, password, or preferences. Information is both stored as and retrieved as an ActionScript object.

The ActionScript programmer has no access to the local file system, so shared objects create no security vulnerability from the user's point of view.

The Shared Object class was designed with the Flash Communication Server in mind. For instance, the onSync event is designed to synchronize all clients of the Flash Communication Server that have a shared object with a particular name. It fires whenever there is any change in the data in the shared object on any client. Each client receives a list of changes in the onSync event. Clients can then update their local shared objects accordingly . That's how the object is shared among all clients.

For more information on The Flash Communication Server, see http://www.macromedia.com/devnet/mx/flashcom/.


Here's an example that creates a local shared object (line 1), stores an attribute in the shared object (line 2), writes the shared object to disk (line 3), accesses the shared object by name (line 4), and retrieves and displays the data that was previously stored (line 5):

 1: mySO = SharedObject.getLocal("userInfo"); 2: mySO.data.userName = "John Smith"; 3: mySO.flush(); 4: backAgain = SharedObject.getLocal("userInfo"); 5: trace (uName = backAgain.data.userName); // "John Smith " 

Notice that a shared object is created with a getLocal method, not a new statement, as shown in line 1. Data is stored as attributes of the data object, as shown in line 2. If you don't flush the information to disk, as in line 3, it will be written to disk before or when the application terminates normally.

The last two lines of the preceding example could occur at a different time, such as after exiting the application or turning the computer off. They can even be part of a different application, as long as an application knows the shared object name to request ( "userInfo" ).

The Stage Object

One of its main purposes of the Stage object is to allow other objects to listen for the Stage.onResize event. The Stage.onResize event handler is typically used to adjust the dimensions or layout of the movie to fit the new size of the window.

For more details on the Stage.onResize event, see "The Stage onResize Event," page 516 , in Chapter 20. "Basic ActionScript").


The Stage object has five properties, two of which are read-only:

  • height Specifies the height in pixels (read-only).

  • width Specifies the width in pixels (read-only).

  • showMenu Determines whether the File-View-Control-Help menu bar is displayed at the top of the standalone Flash Player.

  • align A string property that determines how graphical content on the Stage is aligned. The eight possible values are Top Left ( TL ), Top ( T ), Top Right ( TR ), Left ( L ), Right ( R ), Bottom Left ( BL ), Bottom ( B ), and Bottom Right ( BR ).

    Here's the arrangement:

     TL T TR L    R BL B BR 

    For example:

     Stage.align = "B"; // align at the bottom center 

    The ActionScript interpreter is extremely forgiving of extraneous elements in the string you provide: It simply looks for the first occurrence of one of the acceptable strings, as in this example:

     Stage.align = "^&*&%$#@WBF"; // sets Stage.align to "B" 

    If none of the acceptable strings is present in the string you supply, Stage alignment is set to fully centered (the missing space between L and R in the middle row of the preceding text "diagram"), and the Stage.align property is set to the empty string. For example:

     Stage.align = ""; // align fully centered 

  • scaleMode Specifies the scaling mode of the Flash movie within the Stage. This string property has four legal values: "exactFit" , "showAll" , "noBorder" , and "noScale" . For instance:

     Stage.scaleMode = "noScale"; 

    In the standalone Flash Player (and in the authoring environment), the scaleMode property affects three characteristics of the graphics in a Flash movie: whether the graphics distort or remain proportional; whether the graphics scale when the user changes the size of the Player window; and if the graphics do scale, whether they scale to fit the larger or smaller dimension of the Player window, or both.

    "exactFit" distorts to fill the Stage. That is, it scales to both the larger and the smaller dimension and does not crop the graphic.

    "showAll" remains proportional and scales to prevent cropping. That is, it scales to fit the smaller dimension.

    "noBorder" eliminates any "empty" border at the edges of the stage and scales to the larger dimension. Therefore, it may be cropped in the smaller dimension.

    "noScale" does not scale and therefore may crop in both dimensions.

    If you do not set a scaleMode value, it defaults to "showAll" in the standalone Flash Player and "noScale" in the authoring environment. In the browser, the default Stage.scaleMode is typically "showAll" .

    The behavior that the default scaleMode causes in the browser depends on the setting of the Scale option on the HTML tab in the Publish Settings dialog box.

    Four options on the HTML tab in the Publish Settings dialog box parallel the scaleMode options. (Select File, Publish Settings, and the Scale combo box.) The option you select on the HTML tab affects only parameters in tags in the HTML file. They determine what happens if you edit the HTML file and change the original WIDTH and HEIGHT parameters in the OBJECT tag. The HTML Scale settings do not allow the Flash movie to adjust on the fly as the user changes the size of the browser window.

    The HTML tab setting and Stage.scaleMode do interact. There may be browser and platform (such as Windows versus Mac) dependencies. In general, if Stage.scaleMode is set to "noScale" and the HTML Scale setting is either No scale or Default (Show All), you can change the values of the WIDTH and HEIGHT parameters in the OBJECT tag of the HTML file, and the SWF will not distort to fit the new size.

    Table 21.14 shows some sample settings and what happens if you change the values of the WIDTH and HEIGHT parameters in the OBJECT tag of the HTML file. (Tested with IE 5.5. in Windows.) For instance, the first row of the table tells you that, if Stage.scaleMode is exactFit and the Scale setting on the HTML tab in Publish Settings is No scale, Exact fit, or Default (Show All), the graphic will be scaled to fit both the WIDTH and HEIGHT parameters in the OBJECT tag of the HTML file, distorting the graphic if necessary. On the other hand, if the Scale setting on the HTML tab is No Border, the graphic will scale proportionately (no distortion allowed), so that it fully occupies the larger of the WIDTH and HEIGHT parameters in the OBJECT tag. For instance, if WIDTH is 50 and HEIGHT is 100, the graphic will be 100 pixels high. If the proportionately scaled width is more than 50 pixels, the graphic will be cropped in the horizontal direction.

Table 21.14. Stage.scaleMode and HTML Tab Scale Setting Interaction

Stage.scaleMode

HTML Tab "Scale" Setting

Result in IE 5.5

"exactFit"

No scale, Exact fit, or Default (Show All)

No Border

Nonproportional scaling (distort shape to fit height and width)

Proportional scaling to larger dimension, cropping as necessary

"noScale"

Exact fit or No border

No scale or Default (Show All)

Proportional scaling to larger dimension, cropping as necessary

No scaling

None (default)

No scale or Default (Show All) Exact fit

No border

No scaling

Nonproportional scaling (distort shape to fit height and width) Proportional scaling to larger dimension, cropping as necessary


The TextField and TextFormat Classes

graphics/new_icon.jpg

In addition to the menu attribute, used with the ContextMenu class, the TextField class has two new Boolean attributes ( condenseWhite and mouseWheelEnabled ). The big development, however, is the new StyleSheet class, which allows you to create a StyleSheet object to apply Cascading Style Sheets (CSS).


StyleSheet is the last topic in this section.

condenseWhite determines whether extra "white space" (which includes spaces, line breaks, and paragraph breaks) in an HTML text field should be removed when the field is displayed in a browser. The default value is false . If you set condenseWhite to true , you must use HTML tags such as <BR> and <P> to get line breaks and paragraph breaks in the text field. condenseWhite applies only to HTML text; therefore, if the html property of the text field is false , condenseWhite is ignored.

mouseWheelEnabled determines whether multiline text fields scroll when the mouse pointer is over a text field and the user turns the mouse wheel. By default, mouseWheelEnabled is true .

There are three basic steps to dynamically creating a text field. The steps are as follows:

  1. Create the text field.

  2. Set one or more properties of the field.

  3. Format the field.

The first two come into play for every text field that you create dynamically. The last, formatting, is optional; you can just use default formatting.

Dynamically Creating a Text Field

You create a text field dynamically, using the createTextField method of the MovieClip class. The format is as follows:

 myClip.createTextField ("myTextField",  depth,x,y,width,height  ) 

myClip is the movie clip in which you are creating the new text field. myTextField is the instance name of the new text field. depth is the depth of the text field. x and y are the x and y coordinates of the text field, measured in pixels from the registration point of myClip . width and height are the width and height of the text field, measured in pixels.

For instance:

 myClip.createTextField ("myTextField",2,100,100,25,12); 

This example creates a new, empty text field named myTextField that is a child of myClip , at a depth of 2, 100 pixels to the right of and 100 pixels down from myClip 's registration point. The text field is 25 pixels wide and 12 pixels high.

The newly created text field has a number of properties. For instance, Flash sets the _x and _y properties of the text field equal to the x and y parameters passed to createTextField() . Similarly, Flash sets the _width and _height properties of the text field equal to the width and height parameters passed to createTextField() . Flash also sets the type property to dynamic . All newly created text fields are dynamic unless and until you explicitly set the type property to input .

For a complete list of text field attributes, methods, and events, see Appendix A, "ActionScript Reference," under "TextField Attributes, Methods, and Events."

Setting Properties of the Text Field

A new text field needs to have at least one attribute set, and possibly several, before it becomes useful. You need to do one or more of the following:

  • Set the variable attribute for the text field.

    Because new text fields are automatically dynamic (as opposed to input or static ) text fields, all you need to do is set the variable attribute, and the text field will immediately start displaying the value of the variable you specify.

  • Set the text attribute for the text field.

    The text attribute determines what text will be displayed in the field. Both dynamic and input text fields display the text in their text properties.

  • Make the field an input field by setting the type attribute equal to "input" .

NOTE

You cannot create "static" type text fields dynamically. You can, however, use "dynamic" type text fields exactly like static text fields.


You can have both a variable and a text attribute associated with a single dynamic or input text field, and display the variable and text properties alternately.

Other text field properties you might want to set include the following:

  • border = true to give the text field a border

  • multiline = true to allow the text field to display multiple lines of text, as opposed to just a single line

  • wordWrap = true so that lines of text that are too long for the text field will "wrap" (display on the next line down) automatically

Formatting Using a TextFormat Object

The text field properties mentioned in the preceding section do not format the text. For example, they do not underline, bold, or italicize text. Nor do they set the font, size, or color of the text. To do these types of things, you can create a TextFormat object and apply it to the text field. TextFormat is a class. Use it with the new keyword to create a TextFormat object, as follows:

 myTextFormat = new TextFormat(  font, size, color, bold, italic, underline, url  , target, graphics/ccc.gif align, leftMargin, rightMargin, indent, leading); 

All TextFormat parameters are optional and may be set to null to indicate that they are not defined. Trailing parameters (parameters that come after the last parameter you want to set) can be omitted entirely. Here's an example of creating a new TextFormat object, with red, bold text:

 myTextFormat = new TextFormat(null,null,0xFF0000,true); 

You can set TextFormat properties individually after creating the TextFormat object, as in this example:

 myTextFormat.underline = true; 

Though not as concise , setting properties individually is more readable.

For a complete list of TextFormat attributes and the only TextFormat method, getTextExtent() , see Appendix A, "ActionScript Reference," under "TextFormat Attributes and Methods."


You associate a new TextFormat object with a text field by using the setTextFormat method of the TextField class. For example:

 myTextField.setTextFormat(myTextFormat); 

To associate a new TextFormat object only with new text entered into a text field (for example, when a user is filling in an input field), use the setNewTextFormat() method of the TextField class, as shown in this example:

 myTextField.setNewTextFormat(myTextFormat); 

graphics/troubleshooting_icon.jpg

Losing formatting when you load new text into a text field? See the "Troubleshooting" section at the end of this chapter, page 615 .


Text Format Tags Embedded in HTML Text

You can embed text format tags in HTML text. Embedded tags can be used in addition to, or as an alternative to, TextFormat objects. Embedded tags make it easy to apply an attribute to just part of the text. For instance, in the sample movie htmltags.fla, which follows, the LEFTMARGIN and INDENT attributes apply to both paragraphs of HTML text, whereas the BLOCKINDENT attribute applies to only the second paragraph. Note that everything from line 4 onward is one long line of code.

 1: _root.createTextField("mytext", 1, 50, 50, 300, 100); 2: myText.html = true; 3: myText.wordwrap = true; 4: myText.htmlText = "<TEXTFORMAT LEFTMARGIN=\"12\" INDENT=\"6\"> graphics/ccc.gif <P ALIGN=\"LEFT\"><FONT FACE=\"_sans\" SIZE=\"20\" COLOR= graphics/ccc.gif \"#FF0000\"> This is the first paragraph, with no block indent. < graphics/ccc.gif /FONT></P><TEXTFORMAT BLOCKINDENT=\"30\"> <P ALIGN=\"LEFT\"><FONT graphics/ccc.gif FACE=\"_sans\" SIZE=\"20\" COLOR=\"#000000\"> This is the second graphics/ccc.gif paragraph, with a block indent. </FONT></P></TEXTFORMAT>< graphics/ccc.gif /TEXTFORMAT>"; 


Formatting Using CSS

Formatting using CSS is briefly introduced under "Text: Spelling, Formatting, Translating," page 326 , in Chapter 14, "What's New in Flash MX 2004?"


For a list of StyleSheet methods and the only StyleSheet event, see Appendix A, "ActionScript Reference," under "StyleSheet Methods and Event."


Formatting using CSS is basically a three-step process:

  1. Create a new StyleSheet object.

  2. Add one or more styles to the StyleSheet object.

  3. Apply the StyleSheet object to a TextField object.

Create a New StyleSheet Object

You create a new StyleSheet object with a typical new statement:

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

Notice that the StyleSheet object is a property of the global TextField objectnot of a particular text field.

Add One or More Styles

You can add styles to a StyleSheet object either by loading an external stylesheet ( .css file) using the load method, or by using the setStyle or parseCSS methods in ActionScript, with no external file.

Using an external file is usually preferable. For one thing, you don't have to cut and paste to reuse the same styles in another project. In addition, other programs such as Dreamweaver may be able to use the same external file.

However, the setStyle or parseCSS methods may be useful for adding styles to, or modifying styles loaded from, an existing stylesheet that you don't want to modify. In addition, they allow you to work with no external stylesheet, which may be quicker, and makes your project more self-contained.

The load method has an associated onLoad event that is called after the load completes, either successfully or unsuccessfully. It receives a Boolean parameter, set to true if the load was successful, and to false if the load was unsuccessful.

Here's an example of loading an external stylesheet, with an onLoad callback function that displays the style names if the load is successful:

 myStyleSheet.onLoad = function(success) {   if (success) {     // display style names     trace(this.getStyleNames());   } else {     trace("CSS load unsuccessful");   } } myStyleSheet.load("SEUStudioMX.css") 

Here are a couple of setStyle statements:

 myStyleSheet.setStyle("h2", {   fontSize: '24' }); myStyleSheet.setStyle(".REF",   { fontSize: '12',    color: '#00FF00' }   ); 

Note the use of single quote marks around the CSS values ( '24' ), which are not required in .css files. Also note that the CSS properties are separated by commas, not by semicolons, as they are in a .css file.

You can also create a "style object," giving it attributes that correspond to the ActionScript CSS properties, like this:

 var myStyleObj:Object = new Object(); myStyleObj.color = '#FF0000'; myStyleObj.fontWeight = 'bold'; myStyleSheet.setStyle("em", myStyleObj); delete myStyleObj; 

You can delete the style object after using it in the setStyle method, and you should do so to reclaim the memory that it is using.

The parseCSS method allows you to use standard CSS syntax, using CSS property names rather than ActionScript property names, and using semicolons between properties. In the following example, we create a text string containing a standard CSS style tag named "ref" and then parse it with parseCSS :, adding the "ref" style to the myStyleSheet StyleSheet object. Note that the string starting with ".ref"and shown here on the second and third linesmust actually be written all on one line.

 var cssText:String =     ".ref {color:#ff0000; font-size:20px; [ccfont-style:italic;  text-decoration: graphics/ccc.gif underline; }"; myStyleSheet.parseCSS(cssText); 

Flash MX supports only a limited subset of CSS properties, shown in Table 21.15.

Table 21.15. CSS Properties Supported in Flash Player 7

CSS property

ActionScript property

Supported values

text-align

textAlign

left, center, right

font-size

fontSize

 

text-decoration

textDecoration

none, underline

margin-left

marginLeft

( [*] )

margin-right

marginRight

 

font-weight

fontWeight

normal, bold

font-style

fontStyle

normal, italic

text-indent

textIndent

( [*] )

font-family

fontFamily

 

color

color

Hexadecimal color values

display

display

inline, block, none


[*] Flash looks at the number and applies that to the text, just as if you entered that number in the Properties Panel. It does not distinguish between points (pt) and pixels (px): You can use the number alone, as far as Flash is concerned .

When specifying the font family, mono is converted to _typewriter , sans-serif is converted to _sans , and serif is converted to _serif .

Only hexadecimal color values are supported. RGB colors ( color: rgb(0,102,153 ) and named colors ( blue ) are ignored, and the text remains the default black.

Flash is case sensitive when interpreting ActionScript CSS property names, such as fontSize . If you don't capitalize the S in the middle, for instance, you'll get the default font size.

For CSS properties read from an external .css file, Flash requires them to be all lowercase. This differs from the most browsers, which are not case sensitive when interpreting .css files. This is one reason you frequently have to edit .css files to use them successfully with Flash.

Apply the StyleSheet Object to a TextField Object

Applying a StyleSheet object to a TextField object is simple: Just set the styleSheet attribute of the TextField object to the stylesheet, like this:

 myTextField.styleSheet = myStyleSheet; 

CSS styles work only on HTML text, so assign the text you want to format to the htmlText attribute of the TextField object, as in the following example:

 _root.createTextField("myTextField",10,200,300,400,100); myTextField.styleSheet = myStyleSheet; myTextField.htmlText =    "Here is <span class='REF'>REF style</span> and here is <h2>h2 style</h2>."; 

Other Handy Flash CSS Features

You can get the names of all the styles in a StyleSheet object by using the getStyleNames method. The names are returned in an array. Here's an example:

 var myNameArray:Array = myStyleSheet.getStyleNames(); trace(myNameArray.join("\n")); 

You can get the style object associated with any style, using the getStyle method. The style object is similar to the style object shown previously, used for setting a style. The following code gets a style object and displays all its properties by using a for-in loop:

 emStyleObject = myStyleSheet.getStyle("em"); for (i in emStyleObject) trace (i+" : "+emStyleObject[i]); 

You can use the clear() method to clear all the CSS properties from all the styles in a stylesheet, like this:

 myStyleSheet.clear(); 

The names of the properties remain in the StyleSheet object. After you have cleared the CSS properties, getStyle returns null for all styles.

The TextSnapshot Class

graphics/new_icon.jpg

The TextSnapshot class is designed to let you examine the static, non-selectable text in a movie clip. Instead of being created with a new statement, a TextSnapshot object is returned by the MovieClip.getTextSnapshot method, like this:


 myTextSnapshot = myClip.getTextSnapshot(); 

The following code (textSnap.fla on the CD) should create a TextSnapshot object (line 2), search for the word "test" in it (line 3), set a "select color" of red to highlight selected text (line 4), select the word "test" (line 5), and display the selected text (line 6). It actually does all of that, except set the select color. Apparently, that feature doesn't work as advertised.

 1: searchWord = "test"; 2: var myTextSnapShot:TextSnapshot = myMC.getTextSnapshot(); 3: foundIndex = myTextSnapShot.findText(0,searchWord,false); 4: myTextSnapShot.setSelectColor(0xFF0000); 5: myTextSnapShot.setSelected(foundIndex,foundIndex+searchWord.length,true); 6: trace(myTextSnapShot.getSelectedText()); 



Using Macromedia Studio MX 2004
Special Edition Using Macromedia Studio MX 2004
ISBN: 0789730421
EAN: 2147483647
Year: N/A
Pages: 339

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net