tag enables you to execute ActionScript functions from text fields. You can pass a string value to the specified function. n The scrollV property of input and dynamic text fields enables you to control the portion of a text field value that appears within the text field. maxScrollV returns the highest line number for a given set of text in a text field. n The FlashType rendering engine of the Flash Player enables you to create Flash movies with small text that is more legible than in older versions of the Flash Player.
976
Creating a Game in Flash
C
reating a game requires much more than programming. It is a combination of many skills — game design, interaction design, visual and sound design, and scripting — that brings it all together. These skills also represent the different phases of game design and are covered in this chapter. You must devote your attention to all these aspects of design to produce a successful game.
IN THIS CHAPTER Thinking about game-plan logic Using a document class
To illustrate the different aspects of game design, we deconstruct a simple game, the universally known Hangman.
Using the break and return functions
Before reading through this chapter, copy the ch31 folder on the CD-ROM onto your hard drive. Doubleclick the hangman.html file located inside of the copied folder to play the game in a browser and become acquainted with our project. The functionality of the game is broken down into three custom classes: GameModel, GameView, and GameController. You learn about the purpose of each class file as you proceed with this chapter.
Asking questions with conditionals
ON the CD-ROM
Using arrays Writing ActionScript 3.0 code with an event model Creating text fields dynamically
The Game Plan: Four Phases of Game Design Game development includes the four phases we introduced earlier: game design, interaction design, visual and sound design, and scripting. The following sections discuss those phases in detail.
977
Creating Sprites dynamically Using the Timer class
Part VIII
Applying ActionScript
Many thanks to Jonathan Brzyski for contributing his illustrations to the Flash movie used in this chapter. You can learn more about Jonathan at www.humanface.com/ brzyski. This edition of the Flash Bible uses a modified version of the original hangman.fla file created by Veronique Brossier, discussed in Macromedia Flash MX Bible (Wiley, 2002). We’ve updated this version to use an object-oriented programming model with ActionScript 3.0.
NOTE
Game design Designing a game is creating a fantasy world, a story, and characters with defined roles and goals. It establishes a structure with a clearly defined set of rules and a scoring system. In a single-player computer game, such as the one we created for this chapter, the computer acts both as the opponent and the referee. This traditional Hangman game presents the user with a number of empty slots corresponding to the letters of a word. The player must guess the word, entering one letter at a time. When a player guesses correctly, the letter appears in the appropriate slot. A wrong guess and the hangman is revealed, one body part at a time. It is clearly understood that the hangman is a representation of the state of the user in the game. Being hanged represents defeat, but no harm is done. If the user guesses the word before the body is complete, he or she wins the round; otherwise, the man is hanged, and the user has lost the round.
Interaction design Interaction design is creating the visual representation of the mechanisms of a game: It determines how to play the game and communicates the rules to the user. The interaction of our game is very simple, and the design should be just as simple. To keep the interface to a minimum, the alphabet both represents the choices and displays the user’s selection. The character’s physical state is a character representation of the user as well as an indication of the score within one round. For the Hangman interface, you need the following: n Text fields to display the empty slots for the letters of the word to guess. n A listing of the alphabet that indicates letters already selected as well as ones that remain. This listing is also the device by which the user can select a letter. n A field for feedback from the computer referee. n An area to display the score. n The hangman character.
978
Creating a Game in Flash
Visual and sound design The visual design is essential because it is the first and longest-lasting impression. It communicates the mood of the game. Ours is fun, colorful, and somewhat humorous. This particular game is fairly limited, with not much of a narrative. Nonetheless, the character drawing and animation should keep the user entertained: The hangman is now an alien character going back to the mother ship. Each round was designed with a different set of colors to give some visual diversity. The alien choice is meant to be humorous, both as a homage to the old computer games that used such characters and as a spoof of the multitude of computer demonstrations and illustrations using aliens. The alien character and the background, including the selection of color schemes, were created by Jonathan Brzyski, a talented artist with a sense of humor (see Figure 31.1). Of course, good sound effects are an important complement to the visual. They translate a mood and are helpful to indicate a win or a loss. They also are crucial in supporting and reinforcing animation.
FIGURE 31.1 Our version of the hangman is a tribute to aliens and old computer games.
Scripting Scripting (or programming) a game is the task of asking a series of questions and making decisions, including asking new questions based on the answers, in a language and syntax that the computer can understand. Writing short and task-specific functions is helpful to break down the logic of the game into discrete elements.
979
31
Part VIII
Applying ActionScript
The programmer must deconstruct the game in terms of a dialogue between the computer and the player. It must address every detail, no matter how obvious it seems. By thinking of the flow of events ahead of time, you can write code that can handle several aspects of a problem at different times of your game cycle. Finally, with every new update, Flash provides new functions to simplify our scripting task. Becoming acquainted with them streamlines this process and makes your code easier to write and more elegant. In the ActionScript 3.0 version of the game in this book, we’ve rebuilt the code base for the Hangman game. The three class files associated with the project, GameModel.as, GameView.as, and GameController.as, use a loose interpretation of the Model-View-Controller (MVC) design pattern. There are whole books dedicated to the topic of design patterns in computer programming, and it’s beyond the scope of our chapter coverage to describe this pattern in intricate detail. For starters, though, let’s define a design pattern. A design pattern, when discussed with respect to computer programming, is simply a standard solution to a common programming problem. Because ActionScript 3.0 is object oriented, the Flash developer community has implemented several design patterns from other computer languages in its ActionScript coding practices. Many of our examples in this book simply use a collection of function calls to build interactivity into the Flash movie’s user interface. However, as you start to build more complex Flash movies, you will find that you have to designate roles for each piece of your code — if you just add one function after another on frame 1 of your Main Timeline, pretty soon, you’ll have 600 lines of code with little or no organizing principle. So, a design pattern can help you organize your code because the pattern provides a framework for your code. Of course, you still have to write your own code, but the pattern establishes rules for how operations within the code can be conducted. Let’s break down the design pattern used by this version of the Hangman game. The overarching design pattern is called the Observer pattern. The Observer pattern’s “rule” is fairly simple: An object in your code can facilitate changes to other objects. In ActionScript, you’ve likely practiced this concept a few times when you’ve used the User Interface components in previous examples shown in this book. For example, you can have a button component’s “click” (or Mouse Event.CLICK) event observed by several other components within the movie. With respect to the Hangman game, the Observer pattern enables a core object (called the model) to broadcast changes in the game’s state to other objects, such as a MovieClip instance responsible for displaying the current challenge word and the MovieClip instance responsible for displaying what letter(s) have been selected by the user. The MVC design pattern used by the game consists of three discrete pieces: n Model: The model for the Hangman game is a class named GameModel. This model has the following responsibilities: n Maintain a list of chosen words used within the game.
980
Creating a Game in Flash
n Track the current displayed state of the game, from loading the challenge words from a text (.txt) file to the active/inactive states of the hangman alien pieces. n Check letters selected by the user for matches to the current challenge word. n View: The view for the Hangman game is defined with a class named GameView. GameView is also a Movie Clip symbol in the hangman.fla document’s library. The view contains the necessary graphical elements to display the current game state to the user. For this game, the view consists of the hangman body parts, the artwork behind the hangman, the text fields to display the state of the challenge word, and the text to display the number of wins and losses during the current game. Some of these items, such as the background artwork and the hangman artwork, are created at authortime and placed on the GameView symbol timeline. The text fields, however, are all generated in ActionScript. n Controller: The controller for the game is defined with a class named GameController. The controller is responsible for communicating changes to the game state back to the model. In this game, the controller is fairly simple: a collection of buttons displaying the letters of the alphabet. When the user clicks a letter button, the model is informed of the new letter selection and processes that input accordingly. You learn more about each of these classes as we deconstruct the Hangman game in the rest of the chapter.
Building the Project This section discusses the creation of the art and assets for the interface and then talks about assembling the game’s mechanics. In the tradition of character animation, the alien puppet is constructed of independent Movie Clip symbols for each body part for maximum flexibility. (Figure 31.2 shows the timeline of the headClip symbol in the View Assets ➪ hangMan ➪ hangMan elements folder of the document’s Library panel.) Each Movie Clip in the hangMan elements folder is made of nine frames used for the nine rounds of the game. Each frame displays the same Movie Clip symbol with different advanced color effects. You can view the color settings by selecting the Movie Clip symbol, opening the Properties panel, and clicking the Settings button to the right of the Color menu. Note that by using the color effects, you can use the same symbols over and over, keep your file small, and still develop a very large visual vocabulary. When the game is a loss and the alien is complete, an animation is triggered. This animation uses the beamClip symbol and the BlurFader component. Both of these symbols are attached dynamically in ActionScript, which you’ll see later in this chapter.
981
31
Part VIII
Applying ActionScript
FIGURE 31.2 The headClip symbol uses the head symbol and displays it with different color schemes. This timeline is shown with the Preview in Context option enabled in the timeline window.
Scripting the Game The Hangman game consists of a series of rounds, corresponding to the number of available words to guess. In each round, the computer randomly chooses a word and generates slots as placeholders for the letters. The user attempts to guess the word one letter at a time. For each right guess, the letter appears. For each wrong guess, a piece of the alien character appears. After six wrong guesses, the alien character is completed, does a little animation for us, and the round is over. The score for each round appears on the screen. The three primary states to the game are the setup, user input, and interpretation of the user input. Most of the code for this aspect of the game is located in the class files located in the ch31/src folder on this book’s CD-ROM. The game has an additional feature: The user name and his or her score are saved on the local machine, and the data is available the next time the user plays the game. Most of the code for this feature is located in the GameModel class. However, we cover this feature last.
TIP
982
The SharedObject class enables you to save data locally, similar to the way a JavaScript cookie saves data in a browser.
Creating a Game in Flash
Initializing the Game Before examining the code structure the game uses, you learn about a few of the variables that are vital to structure of the game.
Main Timeline and Document Class overview Open the hangman.fla file in the src folder of the ch31 folder you copied earlier in this chapter. Amazingly, you won’t find any ActionScript code on a keyframe of the Main Timeline. In ActionScript 3.0 and Flash CS4, you can create a document class file that binds to the Flash document upon publishing or testing a movie. The only two layers on the Main Timeline are an embedded font layer and a temporary position reference instance of the GameView class. We talk about the document class and each of these layers in this section.
The Hangman.as document class With the hangman.fla file open, view the Properties panel and make sure nothing is selected on the Stage — you can press the Esc key to deselect active elements. As shown in Figure 31.3, the Properties panel for the Flash file features a Class field, which allows you to link an ActionScript 3.0 class file to the entire Flash document. The hangman.fla file is already linked to a custom class named Hangman, which is part of the com.flashsupport.games package. You do not type the .as file extension for a class file specified in the Class field of the Properties panel. You can also specify the document class in the Publish Settings dialog box. Choose File ➪ Publish Settings, and in the Flash tab, click the Settings button next to the Script version menu. In the Advanced ActionScript 3.0 Settings dialog box, you can edit the document class name.
TIP
In the src/com/flashsupport/games folder of ch31 folder you copied from the book’s CD-ROM, open the Hangman.as file. The actions of this class file, shown in Listing 31.1, establish the following structure, common among any custom class file you might create: n Package name: In ActionScript 3.0, a class file must begin with the package keyword (excluding comments). A package name refers to the path of the class, where it can be found for compiling into the published .swf file. In this example, the package name, com. flashsupport.games, means that this class is stored in the com/flashsupport/ games folder. Simply replace directory separators (/) with a period (.) and you have a package name! When you build your own classes, it’s a good idea to create a unique package name. Most developers use their domain names as a unique identifier, with a reverse order. So, a domain name such as flashsupport.com (which is the domain for this book) becomes com.flashsupport as a package name and folder structure.
983
31
Part VIII
Applying ActionScript
n Import statements: After the package name, the class file lists any class dependencies. For example, if you reference the MovieClip class as a data type in the class, you must specify the class path to the MovieClip class. Unlike actions on the Main Timeline of a Flash document (.fla file), every data type used in a class file requires an import statement. The only exceptions to this rule are data types such as XML, Array, Boolean, Number, String, int, uint, or void. A class path that begins with the name flash. is an intrinsic class of the Flash Player and does not add any additional file size to your published Flash movie. In this example, though, every class inside of the com.flashsupport.games.hangman package is imported, using the wild card character, *. Note that the import statement itself only makes the specified class path(s) available for the ActionScript compiler. If a class file is imported but not used in the actual code, it does not get added to the final Flash movie. n Class name: After necessary class files are imported into the class, you define the class name with the class keyword. In this example, the class name is Hangman. The public keyword enables this class to be accessed by other Flash content, such as a separate movie that loads the hangman.swf file. In general, a document class is declared as a public class. The private keyword has the opposite behavior of the public keyword. If a class member is defined as private, only the class itself has the ability to access that element. Other classes cannot access a private member.
NOTE
n Property declarations: After the class name is declared, public and private variables that can act as properties for the class are listed. For the Hangman class, three variable names — gm, gv, and gc — are reserved for GameModel, GameView, and GameController instances, respectively. The actual instances for these classes are created later in the Hangman class. The one authortime TextField instance named embed_1 is declared as a public variable. n Constructor function: The constructor function is a function with the same name as the class. The Hangman function is automatically invoked when the Flash movie loads. In addition to the trace() output, the constructor function calls the private init method to set up the game. It is not necessary for an ActionScript 3.0 class to have a constructor function — if nothing needs to automatically occur when a new instance of a class is created, you can omit the constructor function.
NOTE
n Methods: The only method in this class is named init, which is automatically invoked by the constructor function. The procedures within this private function are discussed next. The first two sections of code within the init method create an instance of the GameView and GameController classes, gv and gc, respectively. The GameView and GameController
984
Creating a Game in Flash
classes are found in the com.flashsupport.games.hangman package. Note that the data types of the gv and gc instances are the names of these classes. After you cast a data type for a variable, the ActionScript compiler can more thoroughly check your code for errors, letting you know if you’re trying to set a nonexistent property or set a property to an invalid value. We discuss these instances a bit later in this chapter. The GameView instance placed on the gvTemp layer of the Main Timeline is there as a placeholder, to determine where the instance should be placed, in terms of X and Y position, for the new GameView() constructor. This layer is turned into a guide layer to prevent it from exporting in the published (or tested) .swf file.
TIP
The third section of code within the init method creates the model for the game. The model is the central “brain” of the game. The model keeps track of the game state, and determines if the user has correctly selected a letter contained in the challenge phrase. The model does not belong to a DisplayObjectContainer class like the Sprite or MovieClip class as our GameView and GameController instances do. An instance of the GameModel needs to be created at the beginning of the movie in ActionScript code. After an instance is created, there’s only one thing to do with the model: Supply it with the URL (or path) to the data provider for the game. When the new instance of GameModel is created, all the actions in the init() function of the GameModel class are executed. The actions in the init() function set up all the game’s status messages displayed to the user during game play. These messages are stored in the labels property of the GameModel class. You can follow along with the deconstruction of the GameModel class by opening the GameModel.as file in the com/flashsupport/games/hangman folder.
NOTE
In our game, the data provider is a simple text document named words.txt. If you open the words.txt file in a text editor, you can see that the structure is simple: a pipe character ( | ) separates each TV show title in the document. The url property of the GameModel class is known as a getter/setter property, which enables you to process further actions when a new value is set to the property. After a URL is supplied to the GameModel, a chain of events is automatically put into motion within the class: 1. The loadWords() function is invoked. This function creates a new URLLoader instance, and loads the text file into the model. 2. The onWordsLoaded() function is called when the text finishes loading, which converts each line into a separate element in the wordList array property of the GameModel class. 3. The wordList property of the GameModel class is an array containing the words (or more appropriately, challenge phrases) to guess. For our game, the user must guess the names of popular TV shows.
985
31
Part VIII
Applying ActionScript
Some of the challenge phrases contain a space; if a challenge phrase comprises several words, each word is placed on a separate line in the GameView class as defined by the displayWord() function of that class. This additional feature makes the challenge phrase easier to guess, as well as creates a more attractive layout.
NOTE
4. After the wordList property is set, the checkLocalData() function within the GameModel class is invoked. Here, a SharedObject instance named so, which was created in the init() function of the GameModel class, is checked to see if the user previously played the game. If the user’s name, win score, or loss score is found in the SharedObject’s data storage, the game’s state (controlled by the gameState property) is set to GameState.SHOW_STATS. The gameState getter/setter property then broadcasts a new event to any listener of the model. If the user is playing the game for the first time, the gameState property is set to GameState.INIT and the model broadcasts the change to any listener as well.
Going back out to the Hangman document class, the remaining lines of code set up the GameController and GameView instances as listeners of the GameModel instance, gm: gc.model = gm; gc.view = gv; gv.model = gm;
If you go inside of the GameController and GameView class files and search for the model getter/setter properties, you’ll see that the classes register themselves as listeners for specific events from the GameModel class. For example, in the GameController class, the model setter property contains the following code: public function set model(m:GameModel):void { _model = m; m.addEventListener(GameModel.LETTER_PICKED, onLetterPicked); m.addEventListener(GameModel.GAME_STATE, onGameState); }
Here, there are two events that the GameController class needs to listen for: GameModel. LETTER_PICKED and GameModel.GAME_STATE. When the user picks a letter, the GameModel class broadcasts a GameModel.LETTER_PICKED event. When the GameController class hears this event, the onLetterPicked() function within the GameController class is invoked. The GameController class also has a view property, which designates which MovieClip instance is responsible for displaying the game state to the user. In the Hangman document class, you set the view property to the gv instance (an instance of the GameView class). Finally, we also assign the GameModel instance, gm, to the GameView instance, gv. If you open the GameView class file (GameView.as) and find the model setter property, you see which events the GameView class listens for:
986
Creating a Game in Flash
public function set model(m:GameModel):void { trace(“GameView.model > “ + m); _model = m; m.addEventListener(GameModel.WORD_UPDATE, onWordUpdate); m.addEventListener(GameModel.HANGMAN_UPDATE, ; onHangManUpdate); m.addEventListener(GameModel.GAME_STATUS, onGameStatus); m.addEventListener(GameModel.HIT_STATUS, onHitStatus); m.addEventListener(GameModel.GAME_STATE, onGameState); m.addEventListener(GameModel.SCORE_UPDATE, onScoreUpdate); }
The GameModel class broadcasts several events that the GameView class listens to. Each event is assigned to a unique handler within the GameView class.
The shared font layer This layer contains a text field that uses the LabelFont symbol in the Library panel. This font symbol imports the Futura Medium font face from the shared_fonts.swf file located in the ch31/ deploy folder. The shared_fonts.swf file must accompany the hangman.swf file on the Web server or other runtime location. The Futura font face is specified as “Futura Medium” in the TextFormat objects initialized in the createStyles() function of the GameView class. All the TextField instances created by the GameView class use the shared Futura Medium font.
An Overview of Events and the EventDispatcher Class
I
f you write your ActionScript 3.0 class files according to Adobe’s specifications, you should add Event metadata at the top of each class file. If you open the class files associated with this game, you find the events each class broadcasts at the top of the script, just below the import declarations. The syntax for declaring an event is
Event[(“eventName”)]
where eventName is the String value used in the dispatchEvent() function calls you make in the class. In ActionScript 3.0, most classes — including DisplayObjectContainer classes — are descendants of the EventDispatcher class, automatically enabling them to use an event listener framework. Because the GameModel class does not inherit from a DisplayObjectContainer class like the GameController and GameView classes do, the GameModel class is the only class in the game that explicitly extends the EventDispatcher class.
987
31
Part VIII
Applying ActionScript
The placeholder GameView instance This instance is created from the GameView symbol. The instance is named gvTemp and is not included in the published movie. If you look at the properties for the GameView symbol in the Library panel, you can see that the symbol is linked to the GameView.as class file. Open the Library panel, and right-click (or Ctrl+click on Mac) the GameView symbol and choose Properties in the context menu. The advanced view of the Symbol Properties dialog box, shown in Figure 31.3, specifies the com.flashsupport.games.hangman.GameView class path in the Class field.
NOTE
You don’t need to include the .as file extension when you specify a class file.
FIGURE 31.3 The Symbol Properties dialog box
988
Creating a Game in Flash
LISTING 31.1
The Hangman Document Class package com.flashsupport.games { import flash.display.MovieClip; import flash.text.TextField; import com.flashsupport.games.hangman.*; public class Hangman extends MovieClip { private var gv:GameView; private var gc:GameController; private var gm:GameModel; public var embed_1:TextField; public function Hangman(){ trace(“Hangman >”); init(); } private function init():void { trace(“Hangman.init >”); gv = new GameView( -7, -7); addChild(gv); gc = new GameController(); gc.x = 6; gc.y = 220; addChild(gc); gm = new GameModel(); //gm.clearSaved(); gm.url = “words.txt”; gc.model = gm; gc.view = gv; gv.model = gm; } } }
989
31
Part VIII
Applying ActionScript
Building the Interface As you’ve seen in earlier chapters of this book, ActionScript can create a wide variety of runtime assets, such as text fields and sounds. We take advantage of this feature to create the rest of our assets.
Creating text fields The new TextField() constructor method creates a new empty text field instance. Note that after a TextField instance is created, several of its properties are set, such as x position, y position, width, and height. Most important, any newly created asset that needs to be visible on the Stage must be added to the display list with the addChild() method. One of the core functions of the game is the onGameState() function, found in the GameView class. This function controls much of the layout for each state of the game, as shown in the following code: private function onGameState(evt:Object):Void { trace(“GameView.onGameState >”); var stateVal:String = evt.target.gameState; switch(stateVal){ case GameState.INIT: cleanStage(); onFirstPlay(); break; case GameState.SHOW_STATS: cleanStage(); onNextPlay(); break; case GameState.START: cleanStage(); onFirstRound(); break; case GameState.NEW_ROUND: onNextRound(); break; case GameState.LOST: onLost(); } }
990
Creating a Game in Flash
Whenever the GameModel’s gameState property changes, the onGameState() function is invoked. The first thing this function does is retrieve the current state of the game, expressed in the gameState property value of the GameModel (evt.target). For each value of the gameState property, the switch() statement directs the appropriate course of action. For example, when the game player runs the game for the very first time, the gameState property is equal to GameState.INIT. As such, the onFirstPlay() function within the GameView class is invoked, and creates two TextField instances: one to create some descriptive text and another to accept the input from the user’s keyboard. In the following code, the nameField field displays the text “Please Enter Your Name:” (as retrieved from the labels property in the GameView class), and the nameEntryField instance is displayed as an input text field. The btn instance is a button that broadcasts a GameView.START_CLICKED event via the onClick() function within the GameView class. Because the GameController instance, gc (created in the Hangman document class), is listening for this event, the gc instance controls the model, telling it to advance to the next game state. All items created with game state changes are added to the displayedItems property of the GameView class so that the cleanStage() function in the GameView class knows what items to remove between game states.
NOTE
private function onFirstPlay():void { trace(“GameView.onFirstPlay >”); nameField = new TextField(); with(nameField){ x = 46; y = 232; width = 200; height = 20; autoSize = TextFieldAutoSize.LEFT; embedFonts = true; antiAliasType = AntiAliasType.ADVANCED; selectable = false; text = labels[“name”]; setTextFormat(tfOpening); } addChild(nameField); // add nameField instance to displayed items displayedItems.push(nameField); nameEntryField = new TextField();
991
31
Part VIII
Applying ActionScript
with (nameEntryField) { x = 50; y = 250; width = 150; height = 18; background = true; type = TextFieldType.INPUT; defaultTextFormat = tfInput; } addChild(nameEntryField); // add nameEntryField to displayed items displayedItems.push(nameEntryField); btn = new ButtonClip(); with(btn){ x = nameEntryField.x + nameEntryField.width + 5; y = nameEntryField.y - 2; buttonMode = true; addEventListener(MouseEvent.CLICK, onClick); } addChild(btn); // add btn instance to displayed items displayedItems.push(btn); // direct focus to the input field stage.focus = nameEntryField; }
A TextFormat object also can be created and applied to each of these text fields. In the createStyles() function of the GameView class, you’ll see several TextFormat objects created, which are used by the various TextField instances created by other functions in the class.
NOTE
The createStyles() function is invoked in the init() function of the GameView class, as soon as the gv instance appears in the Flash movie at runtime.
When the onFirstRound() function is invoked from the onGameState() function of the GameView class, three TextField instances are created, as shown in Figure 31.4.
992
Creating a Game in Flash
FIGURE 31.4 The statusField instance displays status messages initiated from the GameModel class throughout the game. The lostField and the wonField instances display the score. GameView.hangman instance GameView.word instance
GameView.wonField instance GameView.lostField instance GameLetter instance
GameController.alphabet instance
GameView.statusField instance
Creating the alphabet Sprites can be created dynamically with the new Sprite() constructor method. Furthermore, with ActionScript 3.0’s event framework, both Sprite and MovieClip instances can be used as buttons, as described in earlier chapters. We use the alphabet as both visual feedback of the user selection and an input device for the user to make a selection. To take care of both aspects, we are going to create Sprite instances and then create text fields as their children. The Sprite and MovieClip classes are very similar to each other. If you don’t need a multiframe timeline associated with a MovieClip instance, use the Sprite class instead.
TIP
Because the functionality of each letter button in the alphabet controller is identical, we created a dedicated ActionScript 3.0 class named GameLetter (as defined in the GameLetter.as file found in the com/flashsupport/games/ui folder). This class is utilized in the createAlphabet() function of the GameController class, as shown in the following code:
993
31
Part VIII
Applying ActionScript
private function createAlphabet():void { trace(“GameController.createAlphabet >”); alphabet = new Sprite(); addChild(alphabet); var nXPos:Number = 0; for (var i:int = 65; i <= 90; i++) { var letter:String = String.fromCharCode(i); var gl:GameLetter = new GameLetter(letter); gl.name = “gl_” + letter; gl.x = nXPos; gl.addEventListener(GameLetter.CLICK, onLetterClicked); alphabet.addChild(gl); nXPos += 14; } }
The for() loop of this function cycles through the entire alphabet, creating a new instance of GameLetter for each letter. You can create ASCII characters by using the String.fromCharCode() method, which uses the number corresponding to a letter and returns its corresponding string (A=65, B=66, and so on). Each letter of the alphabet is displayed in the GameLetter instance, as shown in Figure 31.4. The GameController is registered as the event listener for the GameLetter.CLICK event for each GameLetter instance created. GameLetter’s sole purpose is to create a clickable TextField instance. When the user clicks an instance of GameLetter, its GameLetter.CLICK event is broadcast to any listeners. The only listener for each GameLetter instance is the GameController class. When the GameController detects this event, the onLetterClicked() function is invoked: private function onLetterClicked(e:Object):Void { trace(“GameController.onLetterClicked >”); var gl:GameLetter = GameLetter(evt.target); if (controlsEnabled) model.checkLetter(gl.letter); }
If the game is not between rounds, the controlsEnabled property of the GameController is set to true, allowing the checkLetter() function of the GameModel class to be invoked. The letter property of the clicked GameLetter instance is retrieved and passed to the checkLetter () function. This function determines whether or not the clicked letter occurs in any of the character positions of the current challenge phrase. If one or more occurrences are found, the GameView class resets the displayedWord property to a new value, which, in turn, fires a GameModel.WORD_UPDATE event to the GameView class. There the new displayedWord property value is retrieved and rebuilt in the word instance.
994
Creating a Game in Flash
Starting the Game The functions that we cover next are built with the framework of the game in a circular fashion: All the functions are used within one game cycle and again within the next game cycle. This kind of flow is specific to games, and you must keep it in mind when writing code. In particular, game states need to be reset properly at the beginning of a new cycle. At the beginning of each round, some of our assets need to be edited and some variables initialized. The createNewRound() function, defined in the GameModel class, takes care of establishing initial settings for each round in the game: public function createNewRound():void { trace(“GameModel.createNewRound >”); roundNumber++; hangManStates = [ {id: HangmanState.HEAD, active: false}, {id: HangmanState.BODY, active: false}, {id: HangmanState.LEFT_ARM, active: false}, {id: HangmanState.RIGHT_ARM, active: false}, {id: HangmanState.LEFT_LEG, active: false}, {id: HangmanState.RIGHT_LEG, active: false} ]; var avail:Array = new Array(); for(var i:int = 0; i < wordList.length; i++){ var item:Object = wordList[i]; if(item.active) avail.push(i); } var idx:int = Math.floor(Math.random() * avail.length); selectedIndex = avail[idx]; wordList[selectedIndex].active = false; createChoices(); createDisplayedWord(); gameState = GameState.NEW_ROUND; gameStatus = GameStatus.BEGIN_PLAY; } createNewRound() also prepares the states of the hangman character. The hangManStates
property is an array created to store the state of each body part. Because the model is simply tracking states of the game, the model doesn’t need to know which MovieClip objects are actually representing those body parts — that job is the responsibility of the GameView class. If you look at the hangmanStates getter/setter property of the GameModel class, you can see that an event is dispatched every time new values are set:
995
31
Part VIII
Applying ActionScript
public function set hangmanStates(val:Array):void { _states = val; dispatchEvent(new Event(GameModel.HANGMAN_UPDATE)); }
Whenever the GameModel.HANGMAN_UPDATE event is dispatched from the GameModel, the onHangmanUpdate() function is invoked within the GameView class: private function onHangmanUpdate(evt:Event):void { trace(“GameView.onHangmanUpdate >”); var m:GameModel = evt.target as GameModel; var states:Array = m.hangmanStates; var count:int = states.length; for (var i:int = 0; i < count; i++) { var hangmanState:Object = states[i]; var mc:MovieClip = matchStateToClip(hangmanState.id); mc.visible = hangmanState.active; mc.gotoAndStop(m.roundNumber); } }
Here, a for() loop cycles through the states stored within the hangmanStates property of GameModel. The matchStateToClip() function within the GameView class matches the id value shown earlier in the createNewRound() function of the GameModel class to each MovieClip object responsible for displaying that body part. Each body part also jumps to the frame number corresponding to the GameModel’s roundNumber to display a new color scheme. The hangmanStates property is set in two places within the GameModel class: the create NewRound() function (as previously discussed) and the lookForMatch() function. This function sequentially sets the active flag within each object of the hangmanStates array. Initially, at the start of each round,all the hangman’s body parts have their active property set to false. However, if the lookForMatch() function determines that a selected letter is not found within the challenge phrase, the active property of the “next in line” object within the hangmanStates array is set to true. The hangmanStates property is then reset to itself, forcing a GameModel.HANGMAN_UPDATE event broadcast. As such, the onHangmanUpdate() function within the GameView class is called again, setting the visibility of the “next in line” hangman body part to true.
Display the letters of the alphabet The createNewRound() function of the GameModel also sets the gameState property to a value of GameState.NEW_ROUND, which is broadcasted to any listener of this event. The Game Controller class listens for these changes and invokes its positionAlphabet() function.
996
Creating a Game in Flash
This function moves the vertical position of the GameLetter components displaying the clickable letters of the GameController class. This function also sets the text color of each GameLetter instance to black. (Whenever a GameLetter instance is clicked, the text color of the instance is set to gray in the onLetterPicked() function of the GameView class.) private function positionAlphabet():void { trace(“GameController.positionAlphabet >”); for (var i:int = 0; i < alphabet.numChildren; i++) { if(alphabet.getChildAt(i) is GameLetter){ var gl:GameLetter = GameLetter(alphabet.getChildAt(i)); gl.y = 0; gl.letterColor = 0x000000; } } }
Choose a random word The selection of words (or challenge phrases) is stored in an array called wordList, which is defined at the beginning of the game in the GameModel class. In the createNewRound() function, a challenge phrase is randomly picked from the wordList array: var avail:Array = new Array(); for(var i:int = 0; i < wordList.length; i++){ var item:Object = wordList[i]; if(item.active) avail.push(i); } var idx:int = Math.floor(Math.random() * avail.length); selectedIndex = avail[idx]; wordList[selectedIndex].active = false;
The avail array is used to store any challenge phrase that has yet to be played in the game. The for() loop cycles through each object stored in the wordList property and checks its active property. If it hasn’t been played (that is, its active value is true), the object is added to the avail array. After the available challenge phrases have been gathered, a random index number is selected for the avail array. This value is then used to set the selectedIndex property of the GameModel class. The selectedIndex property is used to determine which word is active during the round. In the last line of the previous code block, the active property for that word is set to false so that it can’t be picked again in future rounds. In this version of the game, a word is randomly selected from a pool for each round. As such, the difficulty of each word (number of characters, number of words, and so on) is not ranked. You can modify the game to create a series of word arrays, each one varying in level of difficulty. As the player progresses to the next round, a word from another array can be chosen.
NOTE
997
31
Part VIII
Applying ActionScript
Create the letters of the displayed word The createDisplayedWord() function, invoked from the createNewRound() function of the GameModel class mentioned in the previous section, builds the current state of the displayed word to the game player. At the beginning of the createDisplayedWord() function, we create a String variable named word to hold the individual letters of the displayed word (or challenge phrase). Because the createNewRound() function already set a new selectedIndex value, the selectedItem. label value will be set to the new challenge phrase. In this for() loop, the word variable is built into a series of question marks (“?”) or empty spaces (“ “). So, if the challenge phrase (that is, selectedItem.label) was set to “Lost,” the word variable would equal “????”. Or, if the challenge phrase was “The Office,” the word variable would equal “??? ??????”. After the word string has been generated, the displayedWord property of the GameModel is set to the value of word. private function createDisplayedWord():void { var word:String = “”; var count:int = selectedItem.label.length; for(var i:int = 0; i < count; i++){ word += (selectedItem.label.substr(i, 1) != “ “) ? “?” : “ “; } displayedWord = word; }
Because the displayedWord property’s setter function dispatches the event GameModel. WORD_UPDATE, the GameView class’s displayWord() function is invoked, fetching the new displayedWord property from the GameModel class: private function displayWord():void { trace(“GameView.displayWord>”); if(word is Sprite) removeChild(word); word = new Sprite(); with(word){ x = 35; y = 25; } addChild(word); var displayedWord:String = model.displayedWord; var nX:Number = 0; var nY:Number = 0;
998
Creating a Game in Flash
for (var i:int = 0; i < displayedWord.length; i++) { var chr:String = displayedWord.substr(i, 1); if (displayedWord.substr(i, 1) == “ “) { nX = 0; nY += 30; continue; } var t:TextField = new TextField(); with (t) { x = nX; y = nY; width = 20; height = 20; border = true; embedFonts = true; background = true; selectable = false; antiAntiAliasType = AntiAliasType.ADVANCED; gridFitType = GridFitType.SUBPIXEL; backgroundColor = (chr == “?”) ? 0x99CCFF : 0x9999FF; text = chr; setTextFormat(tfCentered); } word.addChild(t); nX += 25; } }
The displayWord() function completes one primary task: to generate a series of TextField instances displaying each of the characters in the displayedWord value of the GameModel class. A Sprite instance named word is created, and a for() loop cycles over each character of the displayedWord value (represented as the local variable, displayedWord). In each for() loop cycle, a TextField instance is created to display an individual character. If an empty space (“ “) is found in the displayedWord variable, the Y position of the subsequent TextField instance is shifted down 30 pixels. This procedure places each word in a multiword challenge phrase on its own line. You can see this effect in Figure 31.1, where the second line of the word instance is below the first line. The TextField instances of this function use the FlashType rendering engine. Because the centeredFormat instance (a TextFormat instance) uses center alignment, the gridFitType property of the TextField instance is set to GridFitType. SUBPIXEL, to render the text more sharply. For more information about FlashType, read Chapter 30, “Applying HTML and Text Field Formatting.”
CROSS-REF
999
31
Part VIII
Applying ActionScript
The User Input The user enters his or her selection by clicking one of the GameLetter instances in the GameController class, represented in the Flash movie as an instance named gameController on the Main Timeline. When a GameLetter instance is clicked, the onLetterClicked() function of the GameController class is invoked. This function, as discussed earlier in this chapter, submits the letter property of the clicked GameLetter instance to the GameModel’s checkLetter() function.
Interpreting the User Input This process is the bigger part of our project. A series of questions are asked, and their answers determine the next step in the process. You can find the checkLetter() function in the GameModel.as file: public function checkLetter(ltr:String):void { trace(“GameModel.checkLetter >” + ltr ); if (isLeft(ltr)) { lookForMatch(ltr); } else { gameStatus = GameStatus.ALREADY_PICKED; } }
The isLeft() function looks to see if the selected letter was already chosen, and the lookFor Match() function checks the letter against the word to guess.
Was the letter selected before? Using a for() loop, the isLeft() function compares the lettersLeft array to the chosen letter (char), one element at a time. If the letter is contained in the array, the letter is deleted from the array, the selectedLetter property is set to the chosen letter, and the function returns true. private function isLeft(char:String):Boolean { for (var i:int = 0; i < lettersLeft.length; i++) { if (lettersLeft[i].toLowerCase() == char.toLowerCase()) { lettersLeft.splice(i, 1); selectedLetter = char; return true; } } return false; }
1000
Creating a Game in Flash
In ActionScript 3.0, you can specify the data type of the value returned from the function. The data type is declared after the parentheses of the arguments, separated by a colon ( : ). In the isLeft() function, the data type of the return value is Boolean.
NOTE
After the selectedLetter property is set, the GameModel.LETTER_PICKED event is broadcasted from the GameModel to any listeners: public function set selectedLetter(val:String):void { _letter = val; dispatchEvent(new Event(GameModel.LETTER_PICKED)); }
In our code framework, the GameController class is listening for this event, and invokes the onLetterPicked() function, which sets the Y position of the appropriate GameLetter instance 10 pixels below the other GameLetter instances, and changes the color of the text within the GameLetter instance: private function onLetterPicked(evt:Event):void { trace(“GameController.onLetterPicked >”); var ltr:String = evt.target.selectedLetter; trace(“\tltr: “ + ltr); var gl:GameLetter = alphabet.getChildByName(“gl_” + ltr) ; as GameLetter; gl.y = 10; gl.letterColor = 0x666666; }
Is the letter part of the word? The lookForMatch() function of the GameModel class compares the selected letter to the value of the selectedItem.label property, one character at a time, and determines the course of action from the result: private function lookForMatch(char:String):void { trace(“GameModel.lookForMatch > “ + char ); var word:String = selectedItem.label; var display:String = “”; var match:Boolean = false; for (var i:int = 0; i < word.length; i++) { if (word.substr(i, 1).toLowerCase() == char.toLowerCase()) { display += word.substr(i, 1); match = true; } else { display += displayedWord.substr(i, 1); } } displayedWord = display;
1001
31
Part VIII
Applying ActionScript
if (match) { trace(“\tfound match”); hitStatus = HitState.HIT; gameStatus = GameStatus.MATCH_HIT; } else { trace(“\tdidn’t find match...”); for(var j:int = 0; J < hangmanStates.length; j++){ var item:Object = hangmanStates[j]; if(!item.active){ item.active = true; break; } } hangmanStates = hangmanStates; hitStatus = HitState.MISS; gameStatus = GameStatus.MATCH_MISS; } checkStatus(); }
The toLowerCase() method converts the character to lowercase so that the two compared elements match if they are the same letter, regardless of their case. If the letter is found in the selectedItem.label value (represented as the word variable), the corresponding letter is concatenated (or added) to the value of the display variable, which is set to an empty string just prior to the for() loop. If there isn’t a match, the current letter in the displayed state of the word (displayedWord) is retrieved and added to the display variable. If a match is found, the variable match is assigned the value of true. Regardless of the matched letters, the displayedWord property is set to the value of the display variable. The GameView class intercepts the GameModel.WORD_UPDATE event broadcasted by the displayedWord getter property, and redraws the challenge phrase for the user. The rest of the lookForMatch() function changes the values of the hitStatus and gameStatus properties of the GameModel class, depending on the value of match. If a match was found, the hitStatus property is set to HitState.HIT. The GameView class is listening for changes to the hitStatus property, and plays a sound clip of applause (clap.mp3 in the movie’s library). The statusField field of the GameView class also displays a success message to the player. However, if the choice doesn’t match, a for() loop cycles through the objects stored within the hangmanStates property. If the loop finds an object whose active property is false, the active property is set to true and the break action exits the loop. When the hangmanStates property is reset to itself, a GameModel.HANGMAN_UPDATE event is broadcasted from the GameModel. This event is received by the GameView class, which then updates the visibility of the hangman’s body parts. The hitStatus property is also set to HitState.MISS. This
1002
Creating a Game in Flash
value broadcasts the GameModel.HIT_STATUS event to the GameView class, which, in turn, plays the loss.mp3 sound in the movie’s library. After the proper states have been set in the model, the checkStatus() function of the GameModel class is invoked to determine the next state of the game. The next section discusses this function.
Checking the Status of the Game The last step in our process is to check the status of the game. More specifically, is the word complete, is the hangman completely drawn, and/or is the game complete? The checkStatus() function is defined in the GameModel class and asks all these questions. In the following sections, we discuss questions and conditions that exist in the game and the programming logic behind their answers and actions.
Is the word complete? To check whether the word is complete, we check for any remaining ? characters in the letter text fields. We use a for() loop (with the value of the displayedWord.length as the condition to exit the loop). Note how the Boolean variable allMatched is assigned the value of true if the word is complete and false if the word is not complete. var allMatched:Boolean = true; for (var i:Number = 0; i <= displayedWord.length; i++) { if (displayedWord.substr(i, 1) == “?”) { allMatched = false; break; } }
Is the hangman complete? We also need to check the status of the hangman: If all of its parts are visible (that is, active), the round is lost. The alive variable determines whether or not the player is still “alive” during the current round: var alive:Boolean = false; var item:Object; for(var j:Number = 0; i < hangmanStates.length; j++){ var item:Object = hangmanStates[j]; if(!item.active){ alive = true; break; } }
1003
31
Part VIII
Applying ActionScript
If one of the hangmanState objects has an active value of false, the Hangman still has remaining parts to display, and the player is still in the round. As such, the alive variable is set to true. Otherwise, the alive variables remains false.
Are there more words to guess? After the hangmanStates property has been checked, we need to do the same type of check for active words in the game. In others, is it the end of a round, or the end of the game? Has the player played the game long enough to exhaust all the challenge phrases? var wordsAvailable:Boolean = false; for(var k:int = 0; k < wordList.length; k++){ var item:Object = wordList[k]; if(item.active){ wordsAvailable = true; break; } }
How do you end the round? If the player successfully matches all the characters, the gameStatus property is set to GameStatus.WON_ROUND. All gameStatus properties are String constants (see the GameStatus class file) that are looked up in another GameModel property named labels. Therefore, if the gameStatus property is set to GameStatus.WON_ROUND, that index value is looked up in the labels property, which returns the value “You won this round!” Whenever the gameStatus property is updated, the GameView class (as a listener) sets the statusField field to that value, displaying the text to the player. All status messages are declared in the init() handler of the GameModel class. Also, the labels property is actually an associative array, which enables you to use a String value as the key to each element in the array. So, instead of using labels[0] to look up a value in the array, you pass a String value as the key, such as labels[“wonRound”]. Note that the GameStatus.WON_ROUND constant returns the string value “wonRound”.
NOTE
As we continue to break down the GameModel class’s checkStatus() function, you can see that gameStatus is set to GameStatus.WON_ROUND if allMatched is set to true: var reset:Boolean = false; if (allMatched) { gameStatus = GameStatus.WON_ROUND; win++; reset = true; gameState = GameState.WIN; } else if (!alive) { gameStatus = GameStatus.LOST_ROUND;
1004
Creating a Game in Flash
loss++; reset = true; gameState = GameState.LOST; displayedWord = selectedItem.label; }
The win property of the GameModel class is also incremented if the player successfully matchedall the characters in the challenge phrase, and the reset value is set to true. When the win property is updated, the wonField instance in the GameView class updates the current win score.
NOTE
If reset remains false, the GameModel knows that there are remaining words — thus game rounds — to play.
When the gameState property is set to GameState.WIN, the GameView and GameController classes do not respond with any particular action — you could further enhance this game by having the hangman character animate when the player wins the round (that is, provide a bigger payoff to the player for winning the round). If allMatched and alive are false, the player has lost the current round. The gameStatus property is set to GameStatus.LOST_ROUND, the loss value is incremented, reset is set to true, and the gameState property is set to GameState.LOST. The “lost” value tells the GameView class to run the onLost() function, which is described in the next section.
Removing the hangman The onLost() function of the GameView class is executed when the gameState property change is broadcasted from the GameModel class to the GameView class. private function onLost():void { bc = new BeamClip(); bc.x = 245; bc.y = 0; bc.targetClip = hangman; bc.addEventListener(BeamClip.END, removeBeam); addChild(bc); }
This function creates a new instance of the BeamClip class, which is attached to the BeamClip symbol from the library. A variable on the bc instance named targetClip is set equal to the hangman instance. This variable is used by yet another class, BlurFader, found inside of the BeamClip class. In the com/flashsupport/games/hangman folder, open the BeamClip.as file, which is the BeamClip class. This class has a public method named fadeBlur:
1005
31
Part VIII
Applying ActionScript
public function fadeBlur():void { fader = new BlurFader(targetClip, “out”, 0.5); fader.addEventListener(BlurFader.COMPLETE, removeFader); addChild(fader); }
Here, the BlurFader symbol, linked in the Library panel, is dynamically attached to the GameView instance (which is the parent timeline of the BeamClip instance added earlier). The BlurFader component, which we used in Chapter 19, “Making Your First Flash CS4 Project,” uses three parameters: target, dir, and duration. In the new BlurFader() constructor method, we pass these parameters and their values. The fader instance is then set up to make the alien hangman (hangman, as set by the targetClip parameter) fade and blur out from the movie.
Reset the game or just the round? Go back to the GameModel class to resume the deconstruction of the checkStatus function. If all the challenge phrases have been played (that is, wordsAvailable is false) and it’s the end of the current round, the game is over. if (!wordsAvailable && reset) { gameStatus = GameStatus.GAME_OVER; gameState = GameState.GAME_OVER; } else if (reset) { gameState = GameState.ROUND_OVER; }
As such, the gameStatus property of the GameModel class is set to GameStatus.GAME_OVER, which leads to the display of the text “Thanks for playing!” in the statusField instance of the GameView class. The gameState is also set to GameState.GAME_OVER. In this version of the game, nothing happens to the GameView or GameController classes when the game is over — the player simply sees the message and is prohibited from playing further rounds. If there are still challenge phrases left to play and the round is over, the gameState property is set to GameState.ROUND_OVER, which is detected by the GameController class. There, the moveToNextRound() function is invoked three seconds after the event is received from the GameModel. (You can see the Timer class used within the onGameState() function of the GameController class.) The moveToNextRound() function calls the createNewRound() function on the GameModel: private function moveToNextRound(evt:TimerEvent):void { model.createNewRound(); }
The moveToNextRound() function is delayed by three seconds so that the previous gameStatus property change has time to display the current game status to the player in the statusField instance. If the moveToNextRound() function was not delayed, the user would jump right into the next round, missing any updated display of text.
1006
Creating a Game in Flash
Added Feature: Storing User and Game Information Being able to save information opens exciting dimensions to game development. For example, users particularly enjoy playing a multilevel game if they know the next time they visit the site, they can pick up where they left off because the computer remembers which level they last completed and their current score. For our Hangman game, the following section demonstrates a very simple application of saving data onto the user’s local hard drive and recalling it when the player returns to the game at a later time. Flash Player 6 introduced the SharedObject class, which enables you to save data locally, similar to a Web browser cookie. The next time the user runs the game, it displays the saved information. The information can be saved in two ways: when the movie ends or as soon as the information is entered. For our game, the information is saved right away, in the init() function of the GameModel class. The SharedObject.getLocal() method creates a new object named so. so = SharedObject.getLocal(“hangMan”);
To store data in a SharedObject instance, you access the data property of the instance, followed by a variable name. For example, to store a variable named firstName in a SharedObject instance named so, you could use the following code: so.data.firstName = “Scott”;
For the purposes of this game, we check that the data was saved for the username and the win and loss scores. If any of this information is unavailable, the GameModel class dispatches the event GameState.INIT when the gameState property is set to GameState.INIT in the checkLocalData() function of the GameModel class. When the game is played for the very first time, the player enters his/her name. Every time after that, the name and score are remembered and displayed. After the user enters his/her name and clicks the orange button (btn instance of the GameView class) on the screen, the data is saved by calling the saveName() function of the GameModel class: public function saveName(val:String):void { trace(“GameModel.saveName > “ + val); so.data.user = val; so.flush(); }
NOTE
The flush() method of the SharedObject class forces the data to be written to the local data file.
1007
31
Part VIII
Applying ActionScript
The saveScore() function of the GameModel class is called from within the game at the end of each round and stores the win and loss scores. private function saveScore():void { trace(“GameModel.saveScore >”); trace(“\twin: “ + win); trace(“\tloss: “ + loss); if(!isNaN(win)) so.data.winScore = win; if(!isNaN(loss)) so.data.lossScore = loss; var flushResult:Object = so.flush(); trace(“\tflushResult: “ + flushResult); }
And that ends our deconstruction of the Hangman game! We encourage you to modify the elements in the View Assets folder to suit your own particular tastes for the game’s look and feel.
WEB RESOURCE
We’d like to know what you think about this chapter. Visit www.flashsupport. com/feedback to send us your comments.
Summary n Creating a game is much more than programming. It involves other talents, such as game design, interaction design, and visual and sound design. n Scripting a game is asking a series of questions and responding to them appropriately, depending on the user input. n Functions are essential to intelligent programming. Writing small, task-focused functions allows for greater flexibility, particularly for complex games. n Movie Clip instances and text fields can be created dynamically. Additionally, text fields’ properties can be manipulated via ActionScript. In addition to adding flexibility, the creation of runtime instances (versus authortime instances) reduces the file size of your movie. n The Timer class can call a function after a delay period. Here, we are using it to create a delay between rounds. n Using the SharedObject class is a great way to save data on the local drive. We are using it to store the user’s name as well as the game’s score.
1008
Using Components
A
major revolution in past versions of the Flash authoring tool was the addition of a whole new set of components, known as V2 components, and the architecture that they use. Flash CS4 continues to offer the same variety of components, with some modifications to solve minor bugs present in the previous versions. Flash CS4 also offers an entire set of components written in ActionScript 3.0. Components offer an easy way to reuse complicated elements within your movie without having to build them on your own. Although it’s beyond the scope of this chapter, you can also build your own custom components. In this chapter, we take a look at what components are, their parameters, and how to work with many of the components included with Flash CS4. Flash CS4 ships with 22 User Interface components (ActionScript 2.0), 6 Data components (ActionScript 2.0), and several components related to Flash Video playback and control. Flash CS4 has 17 User Interface components written in ActionScript 3.0, as well as updated versions of the FLVPlayback components. The updated FLVPlayback components enable you to play Flash Video files (.flv) with extreme ease. We discuss these components at length in Chapter 16, “Displaying Video.”
TIP
This chapter discusses User Interface (UI) components for ActionScript 3.0. Most of the ActionScript 2.0 UI components use similar, if not identical, operations as those discussed in this chapter.
CAUTION
1009
IN THIS CHAPTER Understanding components Using components in Flash CS4 Using components in your movie Using style properties Embedding fonts Modifying component skins Loading images with the UILoader and ProgressBar components Exchanging and acquiring components
Part VIII
Applying ActionScript
What Are Components? Components are complex Movie Clips with parameters that you define during the authoring process. They are essentially containers, holding many assets that work together to add enhanced interactivity, productivity, or effects to your movies. You can use components to control your movie, such as moving from one frame to another, or to perform more complex tasks, such as sending data to and from a server. We look at many of the components found in the User Interface components set in this chapter. You can download additional components from Adobe and third-party developers to add to those already bundled with Flash CS4, although many of the most useful and regularly used elements, such as buttons, combo boxes, and lists, are already included with the program.
Why Use Components? Components make it easy for you to rapidly create proof-of concepts or prototypes for larger Rich Internet Application (RIA) frameworks, to share your work with other Flash developers who work in your production team, or to share your innovations with other developers in the Flash community. Although this chapter focuses on the components bundled with the release of Flash CS4, the way in which these components are used will also help you understand how other components work — from Adobe or a third party. Components you download sometimes come in sets, which may include many similar small applications. You may need the Adobe Extension Manager to install them into Flash CS4.
CROSS-REF
For more information on exchanging and downloading components, see the section “Exchanging and acquiring components” at the end of this chapter.
One of the arguments against using components is the file size they add to your productions. Even though this may be the case, there are several reasons to use components apart from the ease of dragging them to your Stage and modifying the parameters. Many of the ActionScript 3.0 components in Flash CS4 are substantially large in file size. For example, including a Button component adds 15K to the Flash movie file (.swf) size. Adding a List component contributes 29K to the Flash movie size. However, adding both List and Button components to your movie puts only 31KB into your Flash movie size, not 44K. Why is this the case? Because the List component uses the Button component class, the Button component is already included in the class packages exported to the Flash movie. Flash intelligently includes class files only once, not multiple times.
CAUTION
First of all, usability is an integral part of effective interface design. Components are an extremely effective way of ensuring that your end user understands how to use certain elements of your Flash movie. A predictable interface does not have to be boring or cliché. Furthermore, because components can be skinned, they can have a unique look from one site to the next. The components
1010
Using Components
shipped with Flash CS4, for the most part, are also reliable, given they were built, developed, and tested by professionals. This is not to say that the same level of construction cannot be achieved by thousands of others, but the time and effort spent in complicated coding and testing has already been done for you. And because components are a quick solution to common interface requirements, you will have more time to spend on more complicated and interesting creative tasks instead of repetitive authoring. Exercise care with third-party components — even those that you can download from the Adobe Exchange. Not all components have been thoroughly tested, and some are specifically developed for one particular use in mind. Be sure to test your implementation of a component throughout the development process.
CAUTION
Compiled Clips: A Specific Component Format A component is made up of one or more internal assets. One of the changes introduced with Flash MX 2004’s component architecture (and continued in Flash CS4), though, is that components can be compiled. This means that when you add a compiled component to the Flash document and open your Library panel, you see only one symbol for the component (see Figure 32.1). In Flash CS4, ActionScript 2.0 components are compiled — as such, you cannot easily edit the component skin symbols that comprise a component’s look and feel. The ActionScript 3.0 UI components in Flash CS4 offer the best of both worlds. Although the core component functionality is precompiled, you can easily change the skin symbols used by the component, directly in the Library panel (Figure 32.2).
TIP
FIGURE 32.1 The ComboBox component (ActionScript 2.0) in Flash CS4
1011
32
Part VIII
Applying ActionScript
FIGURE 32.2 The ComboBox component (ActionScript 3.0) in Flash CS4
The symbol type for prepackaged components is called compiled clip. There are a couple of major differences with this component format and architecture: n You can no longer edit the symbols of a component that has been compiled. As such, you need to use ActionScript code to change the appearance of a component. You can also overwrite the linked symbols embedded with a compiled clip with your own new linked assets. n Developers can now create and distribute components without the user being able to easily see the code used to create the component. This is a big “win” for developers who are concerned about their intellectual property rights. If you were familiar with components in older versions of Flash, we highlight other differences between V1 and V2 components throughout this chapter.
1012
Using Components
How to Add a Component You can add a component to your Stage in the following ways: 1. Open the Components panel by going to Window ➪ Components or by pressing Ctrl+F7/Ô+F7. 2. Add a component to the Stage by:
n Double-clicking: You can double-click a component and it will be added to the center of your Document window’s workspace. n Dragging: You can add an instance by clicking the component icon and dragging it onto the Stage. After your component is on the Stage, you can modify its parameters and properties manually in various panels or by using ActionScript code on objects or keyframes in a timeline.
NOTE
You can add additional instances of your component to your document by dragging it from your Library panel onto the Stage instead of from the Components panel.
You can also add an ActionScript 3.0 component to your movie by using the new constructor method in ActionScript after the component is added to your library. An example of adding a Button component to the Stage at runtime and setting a few properties by using ActionScript is as follows. (This code uses standard ActionScript 3.0 syntax.) import fl.controls.Button; var button:Button = new Button(); button.label = “music”; addChild(button);
This creates an instance of a push button, labeled “music,” on the Stage.
Where to Find Components, Assets, and Parameters You can find, control, and edit your components in many areas of the Flash interface. Understanding each of these areas will help you add custom features to your Flash movies that use components.
1013
32
Part VIII
Applying ActionScript
Components panel You can find this panel, shown in Figure 32.3, by going to Window ➪ Components or by using the Ctrl+F7/Ô+F7 shortcut. This panel includes all the components that ship with Flash CS4. If you add components that you have downloaded from other sites, such as the Adobe Exchange, you can access the sets from this panel as well. Each set appears as a new nesting. The Components panel uses a tree structure, in which every set is shown in the panel. The components of each set are nested with each node. The contents of the panel vary based on the ActionScript version of the Flash file. You can change the ActionScript version in the Script menu of the Flash tab of the Publish Settings dialog box (File ➪ Publish Settings).
NOTE
FIGURE 32.3 The Components panel for ActionScript 2.0 (left) and ActionScript 3.0 (right)
1014
Using Components
Component Inspector panel The Component Inspector panel is the central control area for component parameters and bindings. You can find this panel by choosing Window ➪ Component Inspector or by using the Shift+F7 shortcut. In the Parameters tab (Figure 32.4), you can set values for each parameter of a component instance. This tab can also be used to display custom user interface movie files (.swf) for components. The Component Inspector features two additional tabs: Bindings and Schema (see Figure 32.6 later in this chapter). These tabs can be used only with legacy ActionScript 2.0 components. ActionScript 3.0 components cannot use these additional tabs.
FIGURE 32.4 The Component Inspector panel
Library panel After dragging a UI component to the Stage, you will notice a new Component symbol for the component added to your Library panel. If you want to remove a component from your Flash document, be sure to delete it and its assets from the Library panel as well as from the Stage.
Actions panel and ActionScript Not only is there ActionScript hidden within the compiled components that ship with Flash CS4, but you can also write ActionScript to control components or modify their appearance. The builtin components that ship with Flash CS4 have several methods and properties that you can use to customize their functionality. Later in this chapter, you learn how to tap some of these scripted resources.
1015
32
Part VIII
Applying ActionScript
Modifying Component Color Properties and Parameters There are several ways you can easily modify the appearance and functionality of your components. With the Flash CS4 User Interface components, you can customize the face color of each instance with little effort. Let’s look at how you accomplish this. First of all, open the Properties panel. As you have already seen, the Properties panel contains information on the color attributes of your component. This is possibly the easiest and quickest way to change the appearance of your component. Simply by expanding the Color Effect section, you can alter the Brightness, Tint, Alpha, or a combination of these elements by choosing Advanced. You can see the changes made to the face of your component after publishing or previewing your movie. The Parameters tab of the Component Inspector enables you to change the built-in component parameters to ones better matching your site or the usage of your component. For example, on a ScrollPane instance, you can change the horizontalScrollPolicy and verticalScrollPolicy attributes (visibility of horizontal and vertical scrollbars, respectively) in this area by clicking the value area and selecting an option from the list.
CROSS-REF
For more information on changing the look of components, refer to the section later in this chapter called “Modifying Components.”
Removing Components from Your Movie It is important to understand how to properly remove components from your movie. Removing compiled ActionScript 2.0 components is usually very straightforward: Select the compiled clip in the Library panel, and delete it. ActionScript 3.0 components, on the other hand, can often be linked to many other assets spread across several folders in the Library panel. Some components share assets, such as the scrollbar skins. Therefore, care must be taken when removing assets from the library. You should have a solid understanding of component structure and asset usage if you attempt to manually remove items from folders in the library.
Components in Flash CS4 Flash CS4 includes several User Interface (or UI) components, which provide user interface elements and functionality frequently used by developers. You should be able to find a use for some or all of these components at one time or another. Let’s take a look at what each of the core UI
1016
Using Components
components does and how to use them in your movies. After dragging any component instance to your Stage, open up the Properties panel and select the Parameters tab to view the parameters discussed in this section. The parameters for each component discussed in the following sections are also the respective names of each component’s properties. Note that not all of a component’s properties may be exposed in the Component Inspector panel. Also, only the ActionScript 3.0 versions of the components and their respective parameters are discussed.
Button component This component is essentially a standard button with built-in up, over, and down states. The button is designed to resemble an HTML form button (such as a submit button). The Button component, shown in Figure 32.5, is very easy to use and can aid in quick development of mockups or be modified to suit more aesthetically inclined productions. Do not confuse a Button component with a Button symbol. In this chapter, any reference to Button instance implies a Button component, not a Button symbol. In ActionScript 3.0, traditional Button instances belong to the flash.display.SimpleButton class, whereas Button components belong to the fl.controls.Button class.
CAUTION
FIGURE 32.5 The ActionScript 3.0 Button component
Parameters The Button parameters are perhaps some of the easiest to manage. As with other components, you can enter text for the button’s label and add one or more listener functions to execute when the button is pressed. n emphasized: This Boolean parameter determines if a border is drawn on the face of the button in its up state. The default value is false. n enabled: This Boolean parameter determines if the button can be clicked or not. When set to false, the face of the button is dimmed. The default value is true. n label: This is the text appearing on the button face. The default text is simply “Label.” n labelPlacement: This optional parameter is a menu with left, right, top, or bottom options. This setting determines how the label text is aligned to the button’s icon symbol. The default value is right. If you do not use an icon symbol for the instance, this setting has no effect.
1017
32
Part VIII
Applying ActionScript
The icon parameter available in the ActionScript 2.0 version of the Button component is now a style property of the ActionScript 3.0 version. Use myButton. setStyle(“icon”, exported_symbol_name); to assign a custom icon that appears next to the label of the button, where myButton is the instance name of the Button instance, and exported_symbol_name is the class name of the exported symbol asset in the library.
TIP
n selected and toggle: These two parameters work together to enable a Button component instance to act as an on/off button. As a toggle button, the rim of the instance displays an “on” color (dark gray is the default shade color) if selected is set to true. The selected property has no effect if toggle is not set to true. The default value for both the selected and toggle parameters is false. n visible: This parameter determines if the instance can be seen on the Stage when the instance loads. The default value is true.
How it works An instance of a Button component can have regular, disabled, or active states, which can be customized graphically. It is a very quick way to add interactivity to your movie. For additional functionality of the button, you need to write ActionScript by using the Button methods.
TIP
The MouseEvent.CLICK event is sent to any listeners when a Button component instance is clicked.
You can find several examples of the Button component throughout many chapters of this book. You can also search for “button component” in the Flash CS4 Help pages to find more information on the Button component.
CROSS-REF
CheckBox component The CheckBox component, as the name implies, is a user interface element that has a selection box next to text. As with HTML form check boxes, the CheckBox component enables you to easily add form options to a Flash movie. The CheckBox component returns a true or false value. If the box is checked, it returns a true value; if not, it returns false. These states are shown in Figure 32.6.
FIGURE 32.6 The on and off states of the ActionScript 3.0 CheckBox component
Parameters CheckBox parameters can be changed to customize the default label text and its placement in relation to the check box graphic. You can also set the initial state and have the option of setting a function, executing as soon as the button state changes.
1018
Using Components
n enabled: This Boolean parameter determines if the check box can be selected or not. When set to false, the check box graphic and label text are dimmed. n label: This is the name appearing next to the check box. The default value is set to Label. n labelPlacement: This parameter sets the label to the left, right (default), top, or bottom of the check box.
TIP
Make sure to set the height of the instance appropriately to accommodate top and bottom alignment.
n selected: Assigning a true value checks the box initially, although the default value for this is set to false (unchecked). n visible: This parameter determines if the instance can be seen on the Stage when the instance loads. The default value is true.
How it works The CheckBox component has a hit area that encompasses the check box itself, as well as the label next to it. The width of a CheckBox instance can be transformed to accommodate more text. Added functionality using ActionScript is possible by using the methods, events, and properties of the fl.controls.CheckBox class.
ComboBox component The ComboBox component is similar to any standard HTML form drop-down list. When you click the component instance, a list of options appears below the default value in the list. You can also navigate the list by using the Up Arrow, Down Arrow, Page Up, Page Down, Home, and End keys. This component is very useful and essentially has the following two different functionalities: n As a regular combo box, the component can display a list of choices from which the user can select an option. If the combo box has focus, the user can type a letter to jump to a label starting with the same letter (see Figure 32.7). Note that the ActionScript 3.0 version is not shown.
FIGURE 32.7 A standard ComboBox instance, shown closed (left) and open (right)
n As an editable combo box, a user can enter text into the top field to specify a value that is not displayed in the list. The typed value is the active value for the ComboBox instance. Figure 32.8 shows a value being entered into the ComboBox instance at runtime.
1019
32
Part VIII
Applying ActionScript
FIGURE 32.8 An editable ComboBox instance, shown with default display (left) and entered text (right)
Parameters ComboBox parameters can be changed to set labels and data for each item in the drop-down box, set the top of the pull-down to be a text input box (an editable combo box), and customize how many items are viewable when the arrow is selected. n dataProvider: This array is composed of values that correspond to each label and data pair added as an item to the ComboBox instance. For example, if you had a label value of “Red,” you may want a data value of “0xFF0000.” Similarly, if you have a catalog of items, the product’s name may be the label value and its catalog number may be the data value. The user does not see the data value(s). When you set values for the dataProvider array in the Component Inspector panel, the values are typed as strings. You need to set the data values in ActionScript if you want to type the values differently.
NOTE
n editable: This parameter is set to define whether the ComboBox instance can have text entered into the top of the list to specify a value not listed in the menu. This typed value can be passed as data to the movie by using the value property of the ComboBox class. n enabled: This Boolean parameter determines if the combo box can be opened or not. When set to false, the check box graphic and label text are dimmed. n prompt: This parameter sets the text value displayed in the text area of the ComboBox instance when the instance’s selectedIndex property has a value of –1. For example, you could use a text value such as “-- select an option --” to instruct the user to pick a value in the combo box. The default value is an empty string. n restrict: This parameter enables you to restrict the characters that a user can type into a combo box that is editable. You can use a hyphen to specify ranges, such as “A-Z” to allow only the letters A through Z to be typed into the combo box. For more information on how to specify restriction ranges, refer to the Flash CS4 help content for the TextField.restrict property. n rowCount: The number entered here represents how many labels are seen on the dropdown box before a scroll bar appears. The default value is set to 5.
1020
Using Components
n visible: This parameter determines if the instance can be seen in the movie when the instance loads. The default value is true.
How it works When you click the dataProvider field in the Component Inspector panel, you will notice a magnifying glass icon next to the drop-down area. This button, when clicked, opens a Values panel where you can enter the array of values by using the + or – buttons. When a user clicks the ComboBox instance and selects an item, the Event.CHANGE event is broadcast from the instance to its event listeners. Functionality can be added with ActionScript, and the fl.controls.ComboBox class’s methods, properties, and event handlers can be used with each instance of this component.
List component The List component also enables you to create lists just as the ComboBox does, but the list menu is always visible (see Figure 32.9). If there are more items than the height of the instance allows, a scroll bar is automatically added to the list. This component enables selection of one or more items. As with the ComboBox component, keyboard navigation is allowed, and a dataProvider array populates the label and data parameters.
FIGURE 32.9 The ActionScript 3.0 List component at runtime
Parameters The List component (ActionScript 3.0) parameters include an additional option to select multiple values. Other settings in this tab are similar in function to components mentioned earlier. n allowMultipleSelection: This parameter is set to either true or false. A true value enables end users to select multiple values at once when holding down the Ctrl or Ô key. The default value of false allows only one selection to be active at any time. n dataProvider: This array is composed of values that correspond to each label and data pair added as an item to the List instance.
1021
32
Part VIII
Applying ActionScript
n enabled: This Boolean parameter determines if the list items can be selected or not. When set to false, the list and its contents are dimmed. n horizontalLineScrollSize: This parameter determines how much of the horizontal area of the list’s content, in pixels, is scrolled with each click of an arrow button on the horizontal scroll bar of the list. The default value is 4. n horizontalPageScrollSize: This parameter controls how much of the horizontal area of the list’s content, in pixels, is scrolled when the user clicks the scroll track on the horizontal scroll bar of the list. The default value is 0, which indicates the width of the list. n horizontalScrollPolicy: This parameter controls how the horizontal scroll bar for the list is displayed. The default setting of “auto” means a horizontal scroll bar appears only if necessary. A value of “on” ensures that it is always visible, and an “off” value turns it off. n verticalLineScrollSize, verticalPageScrollSize, and verticalScrollPolicy: These parameters behave the same as the corresponding horizontal scroll parameters, except that they control the vertical scroll bar of the list. n visible: This parameter determines if the instance can be seen on the Stage when the instance loads. The default value is true.
How it works This component’s functionality is very similar to that of the ComboBox component. The main difference in a List component is the visibility of the labels and the ability to select multiple values. When a user clicks an item within the List instance, the Event.CHANGE event is broadcast from the instance to its event listeners. If you want to add functionality by using ActionScript, the methods, property, and events of the fl.controls.List class are used. You should know that many ActionScript 3.0 components inherit the List class, such as the DataGrid and the ComboBox components. Any component that is based on the List class can also use a custom cell renderer class, which determines how the content of each row in a List instance is laid out and formatted.
TIP
RadioButton component The RadioButton component looks and feels similar to those found in HTML forms. Based on the design of radio button functionality, only one radio button can be selected within a group of buttons. Figure 32.10 shows a group of RadioButton instances in a Flash movie.
1022
Using Components
FIGURE 32.10 A group of ActionScript 3.0 RadioButton instances
Parameters The RadioButton component has the unique attribute for setting a Group name, which associates the instance with others on the Stage. Other parameters resemble those of components discussed earlier. n enabled: This Boolean parameter determines if the radio box can be selected or not. When set to false, the radio box graphic and label text are dimmed. n groupName: The value of this parameter specifies which group of RadioButton instances on the Stage the particular instance is associated with. Therefore, only one radio dot appears in this group at one time. You can have several groups, each with its own set of associated RadioButton instances. The default value is RadioButtonGroup. n label: This is the text you see alongside the RadioButton instance. n labelPlacement: By default, the label placement is set to the right of the radio button. The options include left, right, top, and bottom. n selected: This parameter sets the initial state of the button to be true or false (default). A false selection is clear. All buttons having the same group name allow only one radio button to be selected at one time. If you set more than one RadioButton instance in the same group to initially have a true value, the last instance is selected when you publish your movie. n value: The value entered here is the data associated with the RadioButton instance. n visible: This parameter determines if the instance can be seen on the Stage when the instance loads. The default value is true.
How it works The groupName parameter is important to understand. Groups of buttons can be added to your document, and in each group, only one button can be selected at a time. Both the RadioButtonGroup and RadioButton classes in ActionScript 3.0 broadcast Event.CHANGE and MouseEvent.CLICK events — you’ll most likely want to create event listeners for the RadioButtonGroup instance, though, rather than for the individual RadioButton instances within the group.
1023
32
Part VIII
Applying ActionScript
You can resize the width and height of an instance with the Free Transform tool, the Properties panel, or the Transform panel to accommodate your label alignment parameter. The hit area of the RadioButton instance surrounds both the button and the label area. Added functionality can be controlled by using the RadioButton class’s methods, properties, and events in ActionScript. It is important to consider the interactive design of your movie when you add radio buttons or check boxes to your movies. Your decision should not be based on the “look” of a radio button versus a check box. Radio buttons should be used only when you need one selection to be made from several choices, and a radio button should never exist outside of a group (that is, you shouldn’t have a single radio button appearing on its own). Check boxes should be used when you need to allow one or more selections to be made from several choices. You can also use a check box for a single option (for example, a form may have a check box asking if you want to receive promotional e-mails for a product). We recommend that you carefully consider how these elements are designed for use in applications because this enhances the usability of your production.
NOTE
ScrollPane component The ScrollPane component is potentially a very powerful and diverse tool. It adds a window with vertical and horizontal scroll bars on either side and is used to display linked symbols from the Library panel on to the Stage. Because the component features scroll bars, you are able to accommodate more content within a smaller footprint on the Stage. Figure 32.11 shows an ActionScript 3.0 ScrollPane instance displaying a linked Movie Clip symbol.
FIGURE 32.11 The ScrollPane component at runtime
Parameters Parameters for the ScrollPane component link it to a Library asset or an external image or SWF file and also control how your end user manipulates the ScrollPane content. You can also control scroll bar positioning and visibility with these parameters: n enabled: This Boolean parameter determines if the check box can be selected or not. When set to false, the check box graphic and label text are dimmed.
1024
Using Components
n horizontalLineScrollSize, horizontalPageScrollSize, and horizontalScrollPolicy: These parameters behave the same way as those for the List component discussed earlier in this chapter. Refer to that coverage for more details. n scrollDrag: Setting this parameter to true enables your users to drag the area within the instance window in order to view the content. A setting of false (default) requires scroll bars to be used instead. n source: Enter a text string set to the class name of a Movie Clip symbol (set to export in the Library panel) or of an external image file (JPEG, PNG, or GIF) or a Flash SWF file that you want to appear in the ScrollPane instance. n verticalLineScrollSize, verticalPageScrollSize, and verticalScrollPolicy: These parameters behave the same way as those for the List component discussed earlier in this chapter. Refer to that coverage for more details. n visible: This parameter determines if the instance can be seen in the movie when the instance loads. The default value is true.
How it works The ScrollPane component can display DisplayObject classes or load external bitmap images or SWF files. If you want to use an internal asset, the Movie Clip (or bitmap image) simply has to be in the Library panel and have the Export for ActionScript setting checked in the Properties dialog box. If you want to further extend the capabilities of the ScrollPane component, refer to the Flash CS4 help pages for the fl.containers.ScrollPane class.
TextArea component The TextArea component (ActionScript 3.0), shown in Figure 32.12, can be thought of as a ScrollPane component for text. The purpose of the TextArea component is to display text or HTMLformatted text within a display window, complete with vertical and/or horizontal scroll bars.
FIGURE 32.12 The TextArea component displaying HTML-formatted text
1025
32
Part VIII
Applying ActionScript
Parameters The settings for the TextArea component in the Parameters tab of the Component Inspector panel control the text that is displayed in the instance. n condenseWhite: This parameter determines if extra white space in HTML text assigned to the htmlText parameter of the component is ignored or not. If set to true, line breaks and extra spaces between words or characters in HTML text are removed, and tags such as
and need to be included in the HTML text to indicate line breaks. If the component does not have any value for the htmlText parameter defined, the condenseWhite parameter is ignored. The default value for this parameter is false. n editable: This parameter controls whether or not the user can change the text in the instance at runtime. The default value is true. If it is set to false, the user cannot change the text. n enabled: This Boolean parameter determines if the user can interact with the controls of a TextArea instance, such as scrolling text with its scroll bars. When set to false, the text and controls of the instance are dimmed.
CAUTION
We strongly recommend that you get in the habit of setting the editable parameter to false. You usually won’t want users to change the contents of your TextArea
component.
n horizontalScrollPolicy: For more details, refer to our coverage of the List component parameter of the same name. n htmlText: This parameter enables you to specify text by using HTML tags in the instance. n maxChars: If the editable parameter is set to true, use this parameter to restrict the amount of text a user can type into the instance. n restrict: Use this parameter to restrict which characters the user can type into the instance. Refer to our coverage of the ComboBox parameter with the same name. n text: The value of this parameter is the actual text displayed in the instance’s text field. For larger blocks of text, draft the text in a separate text editor and copy and paste the text into the text parameter field of the Properties panel. Alternatively, you can set the text property via ActionScript.
TIP
n verticalScrollPolicy: For more information about this parameter, refer to our coverage of the List component parameter with the same name. n visible: This parameter determines if the instance can be seen on the Stage when the instance loads. The default value is true. n wordWrap: This parameter controls how the text wraps in the instance. If the parameter is set to true (default), the text wraps at the visible horizontal boundary of the display area. If the parameter is set to false, the text wraps only when a carriage return or line break is specifically embedded in the text value, or with a
or
tag in the htmlText value.
1026
Using Components
NOTE
Horizontal scroll bars are added only to TextArea instances if wordWrap is set to false and the text width for a line extends beyond the visible display area.
How it works The TextArea component takes the text or htmlText parameter value and displays it within the visible area of the instance. The TextArea component can be further enhanced or controlled with ActionScript, by utilizing the methods, properties, and event handlers of the fl.controls. TextArea class.
CROSS-REF
You can see the TextArea component in Chapter 19, “Making Your First Flash CS4 Project.”
UIScrollBar component The UIScrollBar component, shown in Figure 32.13, can scroll text within your own TextField instances, and you can scroll other MovieClip-based content. (In fact, you can use the UIScrollBar component to control the properties of any object.) The UIScrollBar component can snap to objects on the Stage, and auto-resize its height to match the height of the snapped-to TextField instance. Read our coverage of the scrollRect property of the MovieClip class in Chapter 30, “Applying HTML and Text Field Formatting,” to learn more about using the UIScrollBar component to scroll MovieClip object content.
CROSS-REF
FIGURE 32.13 The UIScrollBar component beside a TextField instance
Parameters The settings for the UIScrollBar component in the Properties panel control the target to which the scroll bar is linked and whether the scroll bar is scrolling horizontal content or vertical content. n direction: This parameter controls the orientation of the scroll bar. By default, the value is “vertical” to scroll content up and down. You can change this value to “horizontal” to scroll content from left to right. n scrollTargetName: This parameter sets which TextField instance is linked to the UIScrollBar instance. This value is automatically filled in if you snap the UIScrollBar
1027
32
Part VIII
Applying ActionScript
instance to a named TextField instance on the Stage at authortime. The TextField instance must be on the same parent timeline as the UIScrollBar instance in order for scrollTargetName to work properly. n visible: This parameter determines if the instance can be seen on the Stage when the instance loads. The default value is true. You can also use the scrollTarget property of the UIScrollBar class in ActionScript 3.0 to set the TextField instance target. It’s also not a requirement to set a scroll target for a UIScrollBar instance — you can use the setScrollProperties() method of the UIScrollBar class to determine the scroll range of an instance, and use the ScrollEvent.SCROLL event of the component with listeners to enable scrolling movement. This technique is used with the scrollRect property of the MovieClip class in Chapter 30, “Applying HTML and Text Field Formatting.”
TIP
How it works When you set the scrollTargetName property to the name of a TextField instance, the UIScrollBar component controls the scrollV or scrollH property of that TextField instance. It can determine the range of the scroll bar movement by looking at the TextField instance’s maxScrollV or maxScrollV property. To learn more about the scrollV , scrollH, maxScrollV, and maxScrollH properties of the TextField class, read Chapter 30, “Applying HTML and Text Field Formatting.”
CROSS-REF
Flash CS4 also includes other UI components written in ActionScript 3.0, including the Label, UILoader, NumericStepper, and ProgressBar components. We discuss the UILoader and ProgressBar components later in this chapter, and an example of the NumericStepper component is available in the CD-ROM files for Chapter 30, “Applying HTML and Text Field Formatting.”
NOTE
Understanding the Listener Event Model for Components Although it’s rather simple to drag and drop components into your Flash document and use the Component Inspector panel to set up initial values for them, the result of any component behavior needs to be described by you, in your own ActionScript code. When the user interacts with a component, a specific event — tailored for the component — is sent out to the Flash movie. Just as you can yell when you’re alone in a forest, the Flash movie just ignores these broadcasted events unless you create something to listen to the events. Such functions are called listeners because their purpose is to intercept broadcasted messages from other objects that generate events — such as components.
1028
Using Components
What a typical listener looks like Just about anything in a Flash movie can be a listener. You can add custom methods to your own classes for example, or you can just create a simple function. To create a basic listener function, use the following syntax: function hearEvent(evt):void { trace(“heard an event!”); }
After you have created a function that behaves as a listener, you can use the function as a listener to a specific component instance.
Letting the component know who its listeners are After a listener function is created, you need to assign the listener function to the component that will be broadcasting events. For our previous example, you could assign the listener to a Button component instance named formButton by using the following code: formButton.addEventListener(MouseEvent.CLICK, hearEvent);
The addEventListener() method requires a minimum of two parameters: the event being broadcast and the listener function. Each component has its own set of event names. The Button component, used in this example, has a click event (represented by the constant MouseEvent. CLICK), which is broadcast to all listeners when the user clicks the Button component instance. All components also broadcast additional information to the listeners, passed as a parameter to the listener’s method. All the UI components pass an event information object to their listeners. The exact properties of this object vary from one component to the next, but some are consistent. In the following listener method, the evt parameter from the Button instance contains several properties, including evt.currentTtarget, which is a reference to the Button instance. function hearEvent(evt:MouseEvent):void { trace(evt.currentTarget + “ was clicked”); trace(“The broadcasted event was “ + evt.type ); } You can change the parameter name to any term you want. In our example, the parameter is referred to as evt, but you can use a term such as event. Just be sure to use the term consistently throughout your listener function.
NOTE
The type property, as you can see in the example code, can tell the listener what type of event was broadcast to it. In this way, you can create one method for a listener and have it handle different event types with specific code. We’ll show you how to create a simple example that demonstrates how a listener works:
1029
32
Part VIII
Applying ActionScript
1. Create a new Flash file (ActionScript 3.0), and save it as button_listener.fla. 2. Rename Layer 1 to submitButton. This layer will hold an instance of the Button component. 3. Open the Components panel (Ctrl+F7/Ô+F7) and drag an instance of the Button component from the User Interface set to the Stage. 4. Select the new instance, and in the Properties panel, name the instance submit Button. 5. Open the Component Inspector panel (Shift+F7), and click the Parameters tab. Assign a new label to the button, such as submit. 6. Create a new layer named actions and place it at the top of the layer stack. 7. Select frame 1 of the actions layer and open the Actions panel (F9/Option+F9). Add the following code to the Script pane: //Button submitButton; submitButton.addEventListener(MouseEvent.CLICK, showEvent); function showEvent(evt:MouseEvent):void { trace(“evt.currentTarget: “ + evt.currentTarget); trace(“evt.type: “ + evt.type); }
8. Save your document and test it (Ctrl+Enter/Ô+Enter). When you click the submit Button instance, you should see the following text in the Output panel: evt.currentTarget = [object Button] evt.type = click
This output illustrates the two properties of the evt object the Button component broadcasts. The event’s name is “click” and the currentTarget property is a reference to the object broadcasting the event, submitButton ([object Button]). If you’re wondering why the trace() action for the evt.type property returns “click” instead of MouseEvent.CLICK, the reason lies behind the constants already defined in ActionScript 3.0. Technically, you could use the following code to add an event listener for this example:
NOTE
submitButton.addEventListener(“click”, showEvent); However, with this syntax, the ActionScript 3.0 compiler has no way of knowing if “click” is a real event — the event name is simply a string value. For example, if you mistyped the event name as “clic”, you would not receive an error when you test the movie — the Button component instance would register the event listener for a nonexistent event. By using a constant such as MouseEvent.CLICK, the compiler has a predefined value it can reference. So, if you mistype the constant, such as MouseEvent.CLIC and test your movie, the compiler issues a warning. Go ahead and try it! Although you do need to type a bit more text for the code, it saves you a headache or two when you’re debugging your code, especially when you’re feeling fatigued.
1030
Using Components
ON the CD-ROM
You can find the completed example file, button_listener.fla, in the ch32 folder of this book’s CD-ROM.
Using Components in Your Movie In the following exercise, you use various ActionScript 3.0 components in a movie to activate and deactivate a series of elements. In the process, you learn how you can use components to build interactivity. The source file for this exercise called components_starter_as3.fla is located in the ch32 folder on this book’s CD-ROM. You will notice several components have been added to the Stage and have been given instance names. You’ll also need to copy the component.txt file from this folder as well.
ON the CD-ROM
1. Open the components_starter_as3.fla file and resave it as components_100.fla. 2. Locate the TextArea instance on the first frame. This instance is already named infoArea. You will write the ActionScript code to dynamically load a text file named component.txt into the movie at runtime. If you open the component.txt file in a text editor, you’ll see that this file declares a variable named intro_text, whose value is used by the TextArea component. Add the code shown in Listing 32.1 to frame 1 of the actions layer.
Here, a URLLoader object named textData loads the component.txt file, and sets the text property of the infoArea component instance to the intro_text variable declared in the component.txt file.
CROSS-REF
For more information on the URLLoader class, refer to Chapter 29, “Sending Data In and Out of Flash.”
3. Save the Flash document and test it (Ctrl+Enter/Ô+Enter). When the movie loads, you should see a trace() message appear in the Output panel indicating whether or not the text file loaded successfully. If it did load, the TextArea component should have filled with the text described in the component.txt file.
Now that text is loading into the TextArea component, you will assign a group name to the two RadioButton instances on the Stage so that they cannot be selected at the same time. 4. On frame 1 of the Main Timeline, select each instance of the RadioButton components. In the Component Inspector panel, enter the same text string into the groupName parameter for each instance. Let’s give the radio buttons a group name of newsGroup, which best describes their purpose in the movie. This identifier places both buttons in the same group.
1031
32
Part VIII
Applying ActionScript
5. Give each instance a different value in the value field in the Properties panel’s Parameters tab. This data is what is returned to the movie indicating the selection. Give the first RadioButton instance, digestButton, a value of digest. For the normalButton instance, assign a data value of normal. 6. It is also a good practice to have one radio button already selected by default. In the Parameters tab for the digestButton instance, set the selected value to true.
Now you are ready to have the “sign me up” button (the signupButton instance) send the movie to the right location, based upon which RadioButton instance is selected. 7. Add the bold code shown in Listing 32.2.
The first line of code adds a code comment to enable code hints for the signupButton instance, and the second new line of code imports the RadioButtonGroup class that was discussed earlier in the chapter. Next, a new listener function, onSignUpClick, is added for the MouseEvent.CLICK event from the signupButton instance. In the onSignUpClick function, the current value of the newsGroup group is assigned to a local variable named val. Notice that the way in which you can retrieve the value of a radio button group is through the selectedData property. If val is equal to “digest” (the value property for the digestButton instance), the movie goes to the digest frame label. If val is equal to “normal” (the value property for the normalButton instance), the movie goes to the normal frame label. 8. Save your Flash document and test it (Ctrl+Enter/Ô+Enter). When you click the “sign me up” button, the movie should jump to the digest frame label. Close the Test Movie window and retest the movie. Now, choose the Normal radio button, and click the “sign me up” button. The movie jumps to the normal frame label.
Let’s activate the ComboBox instance, sectionsBox, so that users who select an item from the menu are automatically taken to a certain area of your movie. This is very similar to what you have accomplished with the RadioButton instances, although you use a different method this time. The instance name of the ComboBox component has already been set to sectionsBox. The values for the combo box’s labels and data have also already been entered for you into the label and data fields, respectively. To make your drop-down box automatically take your user to a different area of the movie, you create a listener function for the sectionsBox instance. 9. Add the bold code shown in Listing 32.3 to the code on frame 1 from Step 7. Here, a function named onSectionChange is created. The function retrieves the currently selected value from the sectionsBox instance (evt.currentTarget.value) and sets that as the value of a frame label used for a gotoAndStop() action. 10. Save your Flash document and test it. Click the ComboBox instance, and choose a section name. When you make a choice, the movie goes to the appropriate frame of the Flash movie.
1032
Using Components
11. Now add a ScrollPane instance to the movie. The ScrollPane component enables you to add an exported symbol or external image asset to a scrollable window. On frame 15 of the pages layer, drag an instance of the ScrollPane component onto the Stage from the Components panel. Size and position the new instance however you prefer. 12. Open the Library panel. Select the file named beach.jpg, and drag it to the Stage. Convert it to a Movie Clip symbol by pressing the F8 key. In the Convert to Symbol dialog box, name the symbol Picture. Assign a registration point in the top left corner. Click the Advanced button in the dialog box. Select the Export for ActionScript check box (which also selects the Export in first frame check box). The Class value should also automatically be set to Picture. See Figure 32.14 for these details. If you receive a warning dialog box after clicking OK in the Convert to Symbol dialog box, just click OK and proceed. Flash CS4 is letting you know that an empty class is automatically being generated for the new Picture symbol.
NOTE
FIGURE 32.14 The settings for the Picture symbol
1033
32
Part VIII
Applying ActionScript
13. Delete the Picture instance from the Stage. An instance of the image is automatically added to the ScrollPane instance at runtime. 14. Select the instance of the ScrollPane component on your Stage. Open the Properties panel, and name the instance imgPane. 15. Open the Component Inspector panel and select the Parameters tab. For the source parameter, enter the string Picture that you set as your symbol’s class name. 16. Save your Flash document and test the movie. Choose new from the ComboBox instance, and, on the new frame, you will see the image within the ScrollPane window. If you want to be able to drag the picture with the mouse, go back to the Parameters tab in the Component Inspector panel and change scrollDrag to true.
LISTING 32.1
The textData Instance //TextArea infoArea; var textData:URLLoader = new URLLoader(); textData.dataFormat = URLLoaderDataFormat.VARIABLES; textData.addEventListener(Event.COMPLETE, showText); textData.load(new URLRequest(“component.txt”)); stop(); function showText(evt:Event):void { trace(“---text file loaded successfully”); infoArea.text = textData.data.intro_text; }
LISTING 32.2
The onSignUpClick() Handler for the Button Component //Button signupButton; //TextArea infoArea; import fl.controls.RadioButtonGroup; var textData:URLLoader = new URLLoader(); textData.dataFormat = URLLoaderDataFormat.VARIABLES; textData.addEventListener(Event.COMPLETE, showText);
1034
Using Components
textData.load(new URLRequest(“component.txt”)); signupButton.addEventListener(MouseEvent.CLICK, onSignUpClick); stop(); function showText(evt:Event):void { trace(“---text file loaded successfully”); infoArea.text = textData.data.intro_text; } function onSignUpClick(evt:MouseEvent):void { trace(evt.currentTarget.name + “ clicked”); var group:RadioButtonGroup = RadioButtonGroup.getGroup(“newsGroup”); var val:String = group.selectedData as String; trace(“\tval: “ + val); if (val == “digest”) { this.gotoAndStop(“digest”); } else if (val == “normal”) { this.gotoAndStop(“normal”); } }
LISTING 32.3
The onSectionChange() Handler for the ComboBox Component //Button signupButton; //ComboBox sectionsBox; //TextArea infoArea; import fl.controls.RadioButtonGroup; var textData:URLLoader = new URLLoader(); textData.dataFormat = URLLoaderDataFormat.VARIABLES; textData.addEventListener(Event.COMPLETE, showText); textData.load(new URLRequest(“component.txt”)); signupButton.addEventListener(MouseEvent.CLICK, onSignUpClick); sectionsBox.addEventListener(Event.CHANGE, onSectionChange); stop(); continued
1035
32
Part VIII
Applying ActionScript
LISTING 32.3
(continued)
function showText(evt:Event):void { trace(“---text file loaded successfully”); infoArea.text = textData.data.intro_text; } function onSignUpClick(evt:MouseEvent):void { trace(evt.currentTarget.name + “ clicked”); var group:RadioButtonGroup = RadioButtonGroup.getGroup(“newsGroup”); var val:String = group.selectedData as String; trace(“\tval: “ + val); if (val == “digest”) { this.gotoAndStop(“digest”); } else if (val == “normal”) { this.gotoAndStop(“normal”); } } function onSectionChange(evt:Event):void { var val:String = evt.currentTarget.value as String; this.gotoAndStop(val); }
ON the CD-ROM
You can find the finished file, components_100.fla, in the ch32 folder of this book’s CD-ROM.
Modifying Components We have already discussed how to alter the color, alpha, or brightness of your component, allowing you to match it to the content on your production. It is a bit more complicated, but not difficult, to change more than just the symbol’s effects in the Properties panel. There are two ways in which you can change the look and feel of Flash CS4 ActionScript 3.0 components: n Use the StylesManager API. n Modify or replace a component’s skins. For the purposes of this introduction to components, you’ll learn how to change the look of components by using styles in ActionScript 3.0.
1036
Using Components
Global style formats You can use ActionScript to change the look of your components. Using ActionScript to change properties is often much easier than doing so manually or making your own graphics. Luckily, you can change attributes of components on an instance or global level — with the help of ActionScript. Most of these changes will be limited to colors, alignment, and text. In Flash CS4, you can control the look and feel of all ActionScript 3.0 UI components in your Flash movie by using the fl.managers.StyleManager class.
ON the CD-ROM
Open the components_100.fla document from the ch32 folder of this book’s CD-ROM to test this new feature.
1. Create a new layer, and rename it global styles. Place this layer above the existing actions layer. 2. On frame 1 of the global styles layer, open the Actions panel (F9/Option+F9), and add the code shown in Listing 32.4.
Here, the setStyle() method is used to apply a new color and font face to all component instances on the Stage. 3. Save the Flash document as components_101.fla and test it. All the components change to the new style settings.
LISTING 32.4
An Example of Using the StyleManager Class import fl.managers.StyleManager; var fontStyle:TextFormat = new TextFormat(); with(fontStyle){ font = “Impact”; color = 0x333333; } StyleManager.setStyle(“textFormat”, fontStyle);_
ON the CD-ROM
You can find the components_101.fla document in the ch32 folder of this book’s CD-ROM.
1037
32
Part VIII
Applying ActionScript
Changing styles for a component class You can also create a custom style for each type of component in your Flash movie. For example, if you want all RadioButton components to use a specific font, you can write ActionScript code to do just that, without having to set a global style or change the style on each individual instance. 1. Open the components_101.fla file created in the previous section. Resave this document as components_102.fla. 2. Select frame 1 of the global styles layer and open the Actions panel. Add the code shown in Listing 32.5 to the existing code. Be sure to add the import fl.controls. RadioButton; line of code to the top of your script along with the other import statements.
This code creates a new TextFormat object named rbStyle. This object uses a different font and color for the text formatting to be applied to all RadioButton instances in the movie. To apply a new TextFormat object for any particular class of component, use this syntax format: StyleManager.setComponentStyle(ComponentClass, styleName, value);, where ComponentClass is the class name of the component you’re controlling with the style.
LISTING 32.5
Changing the Style of a Specific Component Class import fl.controls.RadioButton; var rbStyle:TextFormat = new TextFormat(); with(rbStyle){ font = “Arial Black”; color = 0x3333FF; } StyleManager.setComponentStyle(RadioButton, “textFormat”, rbStyle);
Changing styles for individual instances It is relatively easy to change the font color and face on individual component instances now that you understand style formats. You can accomplish this task by using single lines of ActionScript. Because this code uses fonts in the system, it is important to remember that a default system font is displayed if your end user does not have the particular font installed on his or her system.
CROSS-REF
1038
Using custom font faces and embedded fonts with buttons is covered in the next section, “Using Embedded Fonts with Components.”
Using Components
1. Create a new Flash file (ActionScript 3.0), and save it as component_style.fla. 2. Rename Layer 1 to sampleButton. On frame 1 of this layer, add an instance of the Button component from the Components panel. In the Properties panel, name this instance sampleButton. 3. Make a new layer and name it actions. On frame 1 of this layer, add the following lines of code in the Actions panel: //Button sampleButton; var buttonStyle:TextFormat = new TextFormat(); with(buttonStyle){ font = “Verdana”; color = 0x333333; } sampleButton.setStyle(“textFormat”, buttonStyle);
This sets your button font face as Verdana, with a dark gray color. 4. Save the Flash document and test it. The Button component instance should now have a different appearance.
ON the CD-ROM
In the ch32 folder of this book’s CD-ROM, you can find the completed file, component_style.fla.
Using Embedded Fonts with Components This section explores how to use a custom font for a Button component. There are two ways to accomplish this: Use a dummy text field that embeds the font you want to use in the component, or add a Font symbol set to export from the Library panel. Both involve some ActionScript. First, let’s look at the easier of the two methods. 1. Open the component_style.fla document from the preceding section, and resave the document as component_embedded_font.fla. 2. Select frame 1 of the actions layer and add the following line of code to the existing code: sampleButton.setStyle(“embedFonts”, true);
This new line of code tells the component instance that it should display only embedded fonts. If you tested your movie at this point, the label text for the component would be empty because the Verdana font is not embedded in the movie. 3. Create a new layer and name it embedField. On frame 1 of this layer, select the Text tool and make a dynamic text field off-stage. Give the field an instance name of embedField in the Properties panel. In the Family menu of the Character section of the
1039
32
Part VIII
Applying ActionScript
Properties panel, choose Verdana. Next, click the Character Embedding button in the Character section of the Properties panel. In the Character Embedding dialog box (shown in Figure 32.15), click the Basic Latin option. Click OK to accept this setting. You have now embedded the Verdana font in the Flash movie.
FIGURE 32.15 The Character Embedding dialog box
4. Save your Flash document and test it. The Verdana font (or your substituted font, if applicable) is the font the sampleButton instance uses.
ON the CD-ROM
You can find the completed document, component_embedded_font.fla, in the ch32 folder of this book’s CD-ROM.
If you don’t want to use a dummy text field as this example illustrated, there is another way you can use an embedded font with a component. You can add a Font symbol to the Library panel, and set the font to export with the Flash movie. This method, however, significantly adds more weight (in bytes) to the movie’s file size because all characters in the font are exported with the movie. We highly recommend that you use an empty TextField instance with specific character ranges to minimize the size of your Flash movies.
CROSS-REF
1040
We show you how to embed specific styles of a font in Chapter 30, “Applying HTML and Text Field Formatting.”
Using Components
Modifying AS3 Component Skins You can also edit the skin symbols of ActionScript 3.0 UI components in your Flash movie’s Library panel. For example, if you don’t like the check mark graphic for a CheckBox component, you can add your own background symbol(s) for the CheckBox component to use in place of the default skins. Let’s try this process with the CheckBox component. In the following steps, you learn how to change the check mark graphic of the CheckBox component. 1. Create a new Flash file (ActionScript 3.0) and save it as component_skin.fla. 2. Rename Layer 1 to sampleBox. 3. On frame 1 of the sampleBox layer, drag the CheckBox component from the Components panel to the Stage. In the Properties panel, name the new instance sampleBox. 4. Open the Library panel (Ctrl+L/Ô+L) to view the folders containing the assets for the CheckBox component. Expand the Component Assets folder, and then expand the CheckBoxSkins folder. You’ll find that the check mark graphic is contained within a symbol called CheckBox_selectedIcon, as shown in Figure 32.16. Although this Movie Clip symbol is not set to export, it is included in the other check box symbols set to export. Double-click the CheckBox_selectedIcon symbol to edit the check mark graphic. 5. On the CheckBox_selectedIcon symbol timeline, turn the existing layer (icon) into a Guide layer, and lock and hide the layer. By doing this, you’re preserving the original graphic, just in case you want to go back to it. Create and name a new layer, and draw a new check mark graphic. For our example, we drew an X shape with the Brush tool, as shown in Figure 32.17. To more easily create a new properly sized graphic, use the Zoom tool to magnify the view of the symbol’s Stage. You want to match the original graphic’s size as closely as possible. You can unhide the original Icon layer and turn on the outline mode of the layer to see the original icon shape while drawing your new artwork.
TIP
6. Save the component_skin.fla document and test it (Ctrl+Enter/Ô+Enter). When you click the CheckBox instance in the movie, you should see the new check mark graphic you created in Step 5. You may need to go back and adjust the position and size of your new artwork within the CheckBox_selectedIcon symbol to fit the default background box of the CheckBox component.
ON the CD-ROM
You can find the completed file, component_skin.fla, in the ch32 folder of this book’s CD-ROM.
1041
32
Part VIII
Applying ActionScript
FIGURE 32.16 The CheckBox_selectedIcon symbol in the Library panel
FIGURE 32.17 The new check mark graphic
1042
Using Components
Using the UILoader and ProgressBar Components If you’re thinking it takes too much effort to create your own ActionScript code for preloaders in ActionScript, you may be in luck. Flash CS4 includes two User Interface components, UILoader and ProgressBar, which make the task of loading external files into Flash movies at runtime very simple. Flash CS4 has two sets of User Interface (UI) components: ActionScript 2.0, and ActionScript 3.0. This section discusses the ActionScript 3.0 version. The ActionScript 2.0 UI components are compatible with Flash Player 7 and later, whereas the ActionScript 3.0 UI components are compatible with Flash Player 9 or later.
CAUTION
You might be wondering why we even bothered to have you get your hands dirty, per se, with our earlier coverage of preloading assets in Chapter 28, “Sharing and Loading Assets.” It’s extremely important for you to be able to build your own functionality into your projects. Chances are, you’ll come across situations where components won’t do exactly what you need them to do. As such, you’ll need to know how to build interactivity into your movie on your own.
Adding a UILoader component to your Flash movie The UILoader component can automatically load an external image or .swf file into your Flash movie, and it’s incredibly simple to use. One of the nice features of the UILoader component is that it can scale the image to fit within the boundaries of the component. This example shows you how to use the UILoader component: 1. Create a new Flash file (ActionScript 3.0) and save it as uiloader.fla. 2. Rename Layer 1 to imgLoader. 3. Open the Components panel, and expand the User Interface grouping. Drag the UILoader component to the Stage. Place the instance near the top left corner of the Stage. 4. Select the new instance and name it imgLoader in the Properties panel. 5. Open the Component Inspector panel, and select the Parameters tab. Leave the autoLoad setting at its default value (true). In the source field, type http://www. flashsupport.com/images/beach.jpg. Make sure that the scaleContent setting is true (see Figure 32.18). 6. Save the document and test it. You can watch the asset load into the Flash movie. Understand that the image is being loaded into the Flash movie at runtime, not at authortime. Even though the component displays a live preview of the image in the component on the Stage, it still needs to load the image dynamically when the Flash movie file (.swf) loads into a browser. In other words, the JPEG image is not being imported into the .fla file and exported with the .swf file.
NOTE
1043
32
Part VIII
Applying ActionScript
FIGURE 32.18 The parameters of the UILoader component
ON the CD-ROM
You can find the uiloader.fla document in the ch32 folder of this book’s CD-ROM.
You can use this procedure to load “fixed” content into your Flash movie, meaning, if you don’t need to change the URL of the loaded asset for a given presentation, using the component with hard-coded values in the Component Inspector panel can take care of your needs. However, if you want to be able to change or display several images in the same instance over the course of your presentation, you must know how to change the parameters of the UILoader component instance in ActionScript. In the next section, you learn how to do just that.
Applying the ProgressBar component Now you’ll learn how to use the ProgressBar component with the example you created in the previous section. The ProgressBar component displays the download progress of a loading asset and can be used with the UILoader component. 1. Open the uiloader.fla from the last section. Save this file as uiloader_ progressbar.fla. 2. Open the Components panel and drag an instance of the ProgressBar component from the User Interface grouping to the Stage. 3. Delete the new instance of the ProgressBar component from the Stage. You need to have only the ProgressBar component in the Library panel for use in this exercise. 4. Create a new layer and name it actions. Place this layer at the top of the layer stack.
1044
Using Components
5. Select frame 1 of the actions layer and open the Actions panel. Add the code shown in Listing 32.6.
This code creates a new instance of the ProgressBar component, places it below the UILoader instance, sizes the width of the instance to match that of the UILoader instance, and, most important, sets the source property of the ProgressBar instance to the UILoader instance. The source property tells the ProgressBar instance which asset to monitor. The removeBar function is added as an event listener for the Event.COMPLETE event, which the ProgressBar instance broadcasts when the asset is finished loading. The removeBar function removes the ProgressBar instance from the Stage. 6. Save the Flash document and test the movie (Ctrl+Enter/Ô+Enter). When the UILoader instance begins to load its image asset, the ProgressBar instance displays the percent loaded. When the asset is done loading, the ProgressBar instance disappears.
LISTING 32.6
Adding the ProgressBar Component with ActionScript import fl.controls.ProgressBar; var imgBar:ProgressBar = new ProgressBar(); imgBar.x = imgLoader.x; imgBar.y = imgLoader.y + imgLoader.height + 10; imgBar.width = imgLoader.width; imgBar.source = imgLoader; imgBar.addEventListener(Event.COMPLETE, removeBar); addChild(imgBar); function removeBar(evt:Event):void { removeChild(imgBar); }
Custom Components One of the most exciting aspects of components in Flash CS4 is being able to make your own creations for distribution or reuse. Custom components usually require a significant amount of ActionScript or at least a solid understanding of the language in order to modify an established component. If you learn how to make your own components to suit common requirements, you
1045
32
Part VIII
Applying ActionScript
will inevitably save a lot of valuable development time. Components were created to be easily reused among projects, and they also allow for simple modifications without having to alter the ActionScript code in the component. Given the robust nature of components, you should be able to develop complex applications, detailed right down to custom icons for the library. Although we will not go into detail on how to create custom components in this chapter due to their complexity, we do explore more custom component creation in Chapter 33, “Building an Image Gallery Component.” As discussed earlier in this chapter, components can be compiled clips. Flash CS4 enables you to compile your own custom components so that you can distribute the components without giving away your source code.
TIP
Live preview If you are creating custom components, a Live Preview can be extremely useful. This feature enables you to create an updated view of your component in the authoring environment, so you do not have to publish your movie to view the current state of your component. Creating a Live Preview requires a number of steps to set up your movie structure properly and also to activate ActionScript. It is definitely worth it if you are spending a lot of time creating your own components. If you create a component, a live preview layer is automatically generated for your component. Usually, anything within the component that uses a getter/setter property is automatically included in the automatic live preview in the compiled clip.
TIP
Exchanging and acquiring components After you have made your own components, you may be interested in distributing them. Or you may also be looking for a place to find new prebuilt elements for your Web site. Luckily, there are many extensive resources online where you can find components for download or for submission. A good place to start searching is at Adobe: www.adobe.com/exchange/flash
To install components, you need to download the latest version of the free Extension Manager. There is also a specific method for making your components ready for exchange. You need to package it into a .mxi file, which this Manager can read. The file tells the Manager information regarding the file and the creator. Information about making your components ready for the Extension Manager is available from the same section of the Web site, which includes help and FAQ links.
WEB RESOURCE
1046
We’d like to know what you think about this chapter. Visit www.flashsupport. com/feedback to send us your comments.
Using Components
Summary n Components are a fast and easy way to add interactivity to a movie. They save time and increase usability through consistency, intuitiveness, and solid ActionScript. n Both ActionScript 2.0 and ActionScript 3.0 User Interface components ship with Flash CS4. You cannot edit an ActionScript 2.0 component’s assets in its compiled version. The visual elements of an ActionScript 3.0 component are directly editable in the Library panel. n Some of the most useful UI elements are already built into Flash CS4, including radio buttons, click buttons, combo boxes, lists, and scrolling panes. Using these facilitates user friendliness with your Flash projects because they emulate the user-interface elements commonly used across the Internet and on many desktop applications. n You can change the look and feel of the ActionScript 3.0 components by using the setStyle() method of the individual component or of the StyleManager class. n If you are changing the fonts on your components, you probably want to embed them to avoid problems if your end user does not have the font you are calling for. n Advanced users of Flash may want to create their own custom components. Custom components can be reused from movie to movie, exchanged, or sold on the Internet. You can download additional components to add to your own movie from online resources, such as the Adobe Exchange.
1047
32
Building an Image Gallery Component
I
n Chapter 32, you learned how to use many of the user interface and data components of Flash CS4. Now that you’re familiar with common production tasks associated with components, you can start to learn how to create your own custom components. In this chapter, you learn how to build a Gallery component. By the end, you will know the steps and procedures required to build a fully functional component. Also in this chapter you learn how to build a Flash movie that can dynamically load a list of JPEG files that the user can browse as a series of thumbnails. When the user clicks one of the thumbnails, a larger version of the image loads into the Flash movie. To see the final project, open your browser and go to www.flashsupport.com/fb/as3/gallery.
NOTE
Make sure that you have Flash Player 10 installed to view the completed project.
At this location, you see the interface shown in Figure 33.1. When you click an image thumbnail, the original JPEG loads into the area below the thumbnail bar. The active selection within the bar is highlighted with a bevel filter. When you click another thumbnail, the previously selected thumbnail transitions to a muted grayscale version.
1049
IN THIS CHAPTER Planning and scoping a component Using filter effects with components Storing image information as BitmapData Integrating the Tween class Scripting XML data with PHP
Part VIII
Applying ActionScript
FIGURE 33.1 The completed project
Creating a Plan Before you can start to build the Gallery component, you need to plan the scope of the project. Just what will the component do? We distill the planning process by telling you the component’s features, but in the real world, you will need to brainstorm your ideas and formulate directives for a workable production schedule, accountable to your client’s budget and your time.
CROSS-REF
Read Chapter 3, “Planning Flash Projects,” for more information on production guidelines for Flash projects.
Describing the feature set It might sound too simple to state, but you have to have a plan before you can build anything — even a Flash movie. And more often than not, the lack of proper planning before you start to build a Flash project only results in bigger problems later — the kind that keep you up late at night days before the final delivery date. One of the most common problems that arises early in a Flash project is the desire to overbuild, or add more features to a project than are necessary to satisfy the goals of the project.
1050
Building an Image Gallery Component
The goals we’re aiming to fulfill with the Gallery component include: n Quick updates to images on the server: Many of your business clients love the capability to just upload some images to a server, and voilà — the images are automatically loading into a Flash user interface you designed for them. One of the goals of this project, therefore, is to use server-side scripting (in this case, using PHP as the server-side language) to dynamically read the filenames in a given server folder and deliver that data to the Flash movie. Whenever a new JPEG file is uploaded to that server folder, the PHP script automatically includes the file in the XML feed it sends to the Flash movie. n Unique yet useable interface for browsing images: At the end of the day, if your Flash movie’s user interface is too confusing for a site visitor to understand, the project has lost the potential that Flash offers over standard HTML-based sites. The Gallery component should indicate the state of image browsing clearly, with rollover and rollout states for thumbnail buttons. The thumbnails should also remember if they’ve been clicked previously or not. n Downloadable images: If a user likes an image, he or she should be able to download the image to the desktop. In this component, you learn how to use the new FileReference API to download files directly from the Flash movie. You use this feature with the ContextMenu class to enable the user to right-click the large image area to download the JPEG file currently displayed. In ActionScript 3.0, you can also use the FileReference API to upload files from the user’s computer to your server. Such functionality requires a server-side application or script to receive file uploads.
TIP
n Utilizing JPEG metadata: If you’ve used a digital camera, you know that JPEG images can store a lot of useful data related to the exposure, camera model, flash settings, and so on. You can also use an application like Adobe Photoshop to add more metadata, such as a caption and an author byline. If the JPEG image displayed in the Gallery component has a caption, the component should display the caption below the image. n Dynamic resizing of original JPEG files for thumbnails: With the power of server-side scripting, you can create dynamically resized JPEG images on-the-fly — without ever having to manually create a thumbnail version yourself in a program like Adobe Photoshop. The Gallery component features a property that specifies the URL to a resizing script.
Determining the server-side scripting requirements As mentioned in the previous section, our Gallery component requires the power of server-side scripting to work its magic. We picked PHP as the server-side language to use for this project, although you could adapt the same functionality with any server-side language, including Adobe ColdFusion, Microsoft .NET/ASP, Perl, and so on. One of the reasons we use PHP for this project is that PHP is available on practically every Web-hosting account that you purchase from an Internet Service Provider (ISP) or Internet Presence Provider (IPP). The following list provides the server-side requirements for this project.
1051
33
Part VIII
Applying ActionScript
You can upload the info.php document to your Web server account to discover more details about your server’s PHP installation. You can find this file in the ch33/ finished files/prod/wwwroot folder of this book’s CD-ROM.
ON the CD-ROM
n PHP5: We recommend that you use PHP5 for this project, but you should be able to use PHP4 as well. n GD library: This library enables your PHP scripts to manipulate image data, including the capability to resize JPEG images. Without this library, you won’t be able to create the thumbnail images for the Gallery component. If you run the info.php script on your server, search for the term “gd” to see if the GD library is installed, as shown in Figure 33.2.
FIGURE 33.2 The GD library information as displayed by the info.php script
After you’ve determined that your server has met the core requirements, you’re ready to use the three PHP scripts we’ve included in the ch33/finished files/prod/wwwroot folder on this book’s CD-ROM. You can quickly determine if your server has PHP installed and enabled. Upload the info.php script to an HTTP-accessible folder on your server, and access the info. php script in a browser. If the browser asks you to download the info.php file, your server most likely does not have PHP enabled.
TIP
1052
Building an Image Gallery Component
It’s beyond the scope of this chapter to discuss the PHP scripting used in each script file. We provide a basic overview of the each file’s functionality in the following sections. We encourage you to open the PHP files in your preferred text editor to review the syntax. For the PHP experts out there, note that the $doc_root variable (found in both the files.php and resize.php scripts) uses a nonstandard way — for portability reasons — to determine the document root of the server. The syntax we use enables the scripts to function properly in both Windows IIS server and Apache Web server environments. Feel free to modify any of the scripts to suit your particular needs.
NOTE
files.php This script dynamically reads a specified server folder to search for JPEG files and displays the found JPEG files in an XML document. You must pass a directory name, either relative or from the server root, as a variable named dir. For example, if you specify files.php?dir=images/
the script looks for a folder named images in the same folder where the files.php script resides. You can also specify a directory with the syntax: files.php?dir=/gallery/images/
which tells the script to look for a folder named gallery at the server root, and then looks for a folder named images within that gallery folder. To see a sample XML document created by this script, type the following URL into a Web browser: www.flashsupport.com/fb/as3/gallery/files.php?dir=images/
When this page loads, you should see the XML data shown in Listing 33.1. (Note that the ; character indicates a continuation of the same line of code.) The schema for this XML file uses a parent node named , which contains several child nodes named . Each tag represents a JPEG file found in the images folder. The files.php script retrieves all the information listed for each JPEG file, including the image’s width and height (in pixels), the path to the image on the server (src), the caption stored within the JPEG’s metadata (if a caption exists), and the name of the file (filename) without the directory path. In order for the files.php script to function properly, the JPEG-Meta.php script must be located in the same server folder as the files.php file. We discuss the JPEG-Meta.php script later in this section.
NOTE
The XML data provided by the files.php script is loaded into the Flash movie, which turns the XML data into an array to pass as a data provider to the Gallery component.
1053
33
Part VIII
Applying ActionScript
LISTING 33.1
The XML Data for the JPEG Files
1054
Building an Image Gallery Component
resize.php This PHP script performs the task of resizing a copy of the original JPEG image to fit a specific height. In this project, the Gallery component’s thumbnails should be 50 pixels tall. The resize. php script requires two parameters: height and img. The height parameter should be an integer value, while the img parameter specifies the path and name of the JPEG file to resize. For example, if you type the following URL into a browser, you should see a picture of a beach on Prince Edward Island, Canada, resized to a height of 50 pixels: www.flashsupport.com/fb/as3/gallery/resize.php?height=50&img=/images/ beach.jpg
With the Gallery component, you can specify the resize.php script as the value of the thumbScript property. You can quickly determine if you have the GD library installed (and/or enabled) on your server by uploading the resize.php script to a publicly accessible folder and accessing the script in the browser as we demonstrated with the beach picture. Specify an img path that points to a JPEG you’ve uploaded to another folder on the server.
TIP
JPEG-Meta.php This amazing script, provided to us by Rob Williams at CommunityMX.com, enables the files. php script to retrieve the metadata, if any exists, of each JPEG file in the specified folder. This script must be uploaded to the same folder as the files.php script. Without this file, the files.php script does not function. For more information about using Rob William’s PHP script, read his tutorial at CommunityMX.com. You can find a link to this tutorial in the PHP Utilities section of the www.flashsupport.com/links page.
WEB RESOURCE
NOTE
You also need to upload the JPEG images to your server, into a folder whose path you specify with the files.php script from the Flash movie.
Phase 1: Setting Up the Gallery Class On this book’s CD-ROM, in the ch33 folder, you can find two folders: starter files and finished files. Each folder has the same structure, featuring src and deploy folders. The src folder contains all the source files, such as .fla files and ActionScript files, and the deploy folder contains all the production-ready files that should be uploaded to the server for final deployment.
CROSS-REF
You can learn more about our src and deploy folder structures in Chapter 3, “Planning Flash Projects.”
1055
33
Part VIII
Applying ActionScript
Reviewing the starter files Let’s review the files that have already been built in the starter files folder. You can access each of these files from the gallery.flp file in the Project panel.
EasyFilter.as This class file, which can be found in the src/flash/com/themakers/effects folder, contains one method named saturate. This method can create a ColorMatrixFilter instance. This filter is the ActionScript class responsible for enabling the Adjust Color filter available for MovieClip and TextField instances in the Filters section of the Properties panel. For the Gallery component, you use the EasyFilter.saturate() method to easily control the saturation color values of thumbnail images. The saturate() method accepts values from –100 to 100, just like the Saturation slider in the Adjust Color filter of the Filters tab of the Properties panel. The following code sample illustrates a typical use of the method: import com.themakers.effects.EasyFilter; var myLogo:MovieClip; myLogo.filters = [EasyFilter.saturate(-50)]; Many thanks to Joey Lott and Guy Watson for their help with creating the ActionScript code within the saturate() method. It’s beyond the scope of this book to discuss the intricacies of using matrix values with the ColorMatrixFilter class — look to ActionScript 3.0 Bible (Wiley, 2008) for more information.
NOTE
main_starter.fla This Flash document contains the basic layout for the Gallery component and can be found in the ch33/starter files/dev/flash/main_starter.fla folder. If you open this file, you can see that the Main Timeline of the movie has three layers: n _captionField: This layer has a TextField instance of the same name. The instance is located near the bottom of the Stage. This field displays the caption text for the JPEG image. This field also embeds most of the Basic Latin characters for the Arial font, and the field uses the new Anti-alias for readability setting in the Properties panel. Note that not all JPEG images have caption metadata — we specifically added caption data to each sample JPEG image in the project, using Adobe Photoshop’s File ➪ File Info command. n _scrollPane: This layer has a ScrollPane component of the same name. The instance is located at the top of the Stage. The ScrollPane instance stores Sprite holders for each of the loaded JPEG thumbnail images.
1056
Building an Image Gallery Component
n _loader: This layer has a UILoader component of the same name. The instance is located below the ScrollPane instance. When a user clicks a thumbnail image in the ScrollPane instance, the full-size JPEG image loads and scales within the width and height of the UILoader instance. The publish settings for the main_starter.fla file have already been set up to publish the .swf and .html files for the document to the deploy folder. The .swf file is named main.swf, and the .html file is named main.html.
Constructing the Gallery component Before you start to modify the starter files, create a copy of the starter files folder on your computer. In the following steps, you learn how to create a Gallery class file for the Gallery component. Then you associate the class with a new Gallery clip in the Library panel.
ON the CD-ROM
Make a copy of the c33/starter files folder on your computer.
1. Browse to the src/flash/com/themakers folder in the starter files folder you copied. 2. Create a new folder named portfolio. This folder is used to store the Gallery.as file you create in the next steps. This folder could also be used to store other class files related to a portfolio set of components, such as a gallery chooser. 3. Create a new ActionScript document by choosing File ➪ New and selecting ActionScript File in the New Document dialog box. Save the new ActionScript file as Gallery.as in the src/flash/com/themakers/portfolio folder you created in Step 2. 4. In the Gallery.as script file, add the code shown in Listing 33.2. This code declares the package name, imports all the necessary ActionScript 3.0 (AS3) classes that the Gallery class requires, and creates the constructor for the class. We discuss many of the imported classes as we add further portions of code to the class. For now, you declare three variables representing the three elements currently on the Stage of the main_starter.fla document. The class constructor invokes the init() function, which contains a trace() action to indicate that the class has instantiated. 5. Save the Gallery.as file. 6. In Flash CS4, open the main_starter.fla file located in the src/flash folder. 7. In the Timeline window, select all the frames, from top to bottom, across the three layers. Right-click (or Control+click on Mac) the frame selection, and choose Copy Frames from the contextual menu.
1057
33
Part VIII
Applying ActionScript 8. Choose Insert ➪ New Symbol. In the Create New Symbol dialog box, type Gallery in the Name field. Make sure that the advanced settings are displayed — if not, click the Advanced button in the lower right corner of the dialog box. In the Linkage section, select the Export for ActionScript check box. The Class field should automatically fill with the name Gallery. Replace this name with the text com.themakers.portfolio. Gallery. This path points to the Gallery.as file you saved in Step 5. Note that the path is relative to the main_starter.fla document and does not include the .as file extension. As Listing 33.2 shows, the Gallery class extends the Sprite class. As such, the Base class field in this dialog box should contain the path for the Sprite class, which is flash.display.Sprite. (See Figure 33.3.) Click OK.
TIP
You can assign global class paths in the Flash tab of the Publish Settings dialog box — click the Settings button next to the Script menu.
9. In the new timeline of the Gallery symbol, select frame 1 of Layer 1. Right-click (or Control+click on Mac) the frame, and choose Paste Frames. The elements from the Main Timeline should now be pasted into the Gallery symbol timeline. Note that the layer names are automatically copied as well. 10. With all the elements selected on the Stage, open the Properties panel. The elements are not aligned to the top left corner of the symbol’s registration point. In general, it’s considered best practice to align elements within components to the top left corner. In the Properties panel, change the X position to 0 and the Y position to 0. When you deselect the elements on the Stage, the registration point should be at the top left corner of the ScrollPane component.
Believe it or not, that’s all you need to do on the timeline of the Gallery symbol. Everything else happens within the Gallery.as file. Remember, because you attached the Gallery class in the Class field for the Gallery clip, all the code within the class file is automatically associated with the symbol. If you want to change the embedded font used for caption text, select the _captionField instance on the Stage of the Gallery clip and change the font name in the Properties panel.
TIP
11. Go back to the Main Timeline (Edit ➪ Edit Document). Create a new layer named gallery, and delete the other layers. 12. Open the Library panel (Ctrl+L/Ô+L), and drag an instance of the Gallery symbol on to the Stage. Place the instance near the top left corner of the Stage. In the Properties panel, name the instance gallery. 13. To make sure that the Gallery.as class file is attaching correctly to the Gallery symbol, save the Flash document and test it (Ctrl+Enter/Ô+Enter). When the movie loads, you should see the Gallery.init > statement appear in the Output panel. If this message does not appear, right-click (or Control+click on Mac) the Gallery clip in the Library panel, choose Properties, and check the Class path value.
1058
Building an Image Gallery Component
FIGURE 33.3 The Create New Symbol dialog box
LISTING 33.2
The Gallery Class Constructor package com.themakers.portfolio { import import import import import import import import import import import
flash.display.Bitmap; flash.display.BitmapData; flash.display.Sprite; flash.text.TextField; flash.events.ContextMenuEvent; flash.events.Event; flash.events.MouseEvent; flash.filters.BevelFilter; flash.filters.BlurFilter; flash.net.FileReference; flash.net.URLRequest; continued
1059
33
Part VIII
Applying ActionScript
LISTING 33.2 import import import import import import
(continued)
flash.ui.ContextMenu; flash.ui.ContextMenuItem; fl.containers.ScrollPane; fl.containers.UILoader; flash.events.ProgressEvent; com.themakers.portfolio.Thumbnail;
public class Gallery extends Sprite { public var _scrollPane:ScrollPane; public var _loader:UILoader; public var _captionField:TextField; function Gallery(){ init(); } private function init():void { trace(“Gallery.init >”); } } }
You can find this version of the main_starter.fla file as main_100.fla in the ch33/in_process folder. The Listing33-1.as file located in the ch33 folder can be renamed to Gallery.as and inserted into your portfolio folder.
ON the CD-ROM
Phase 2: Loading Thumbnails into the ScrollPane In this section, you learn how to modify the Gallery.as and main_starter.fla files to load JPEG thumbnails from your PHP-enabled server.
Uploading scripts and images to your Web server Before you can continue to modify the Flash documents for this project, you need to upload the files in the starter files/deploy folder to a publicly accessible location on your PHPenabled server. If possible, try uploading the files to the HTTP document root of the server. For example, if your site’s domain is www.mydomain.com, try putting the PHP script files at the document root where you can load them by typing the following URL into a browser: http://www.mydomain.com/info.php
1060
Building an Image Gallery Component
Also, if you have directory browsing enabled on your server, you should be able to access the images folder (and browse the image files within) by typing: http://www.mydomain.com/images
After you’ve completed the project, you can move your script files and images to other folders and modify the script parameters in the Flash movie as needed. You can also configure a local HTTP server on your computer for testing purposes. During the writing of this chapter, we used PHP5 with Microsoft IIS on Windows XP. If you test locally, make sure that http://localhost/info.php loads properly before continuing.
TIP
Building data properties for the Gallery class After you have uploaded the wwwroot files to your own server, you’re ready to go back to Flash production tasks. In this section, you add several data properties to the component, enabling the component to access the resize.php script and to store the JPEG file information for the Gallery. 1. Go back to the Gallery.as file you created in Phase 1 and add the bold code shown in Listing 33.3. This new code creates the following properties. Each property has an associated private variable listed at the top of the class.
n items: This property saves an array of JPEG filenames in the _data private variable. The items property is accessed later in this chapter when the thumbnails are built. Whenever information related to the active thumbnail or JPEG image displayed in the UILoader component is needed, the items property can be utilized. n rootURL: This property stores a root path to the server with the PHP scripts and images. This value is appended to image URLs used throughout the class. The private variable _rootURL stores the String data associated with this property. n thumbHeight: This property stores the height, in pixels, that should be passed to the resize.php script for the creation of the thumbnail images. The private variable _thumbHeight stores the value for this property. n thumbScript: This property stores the name of the script file to call for dynamic resizing of the JPEG images as thumbnails. The default value is set to resize.php, the script file you’ve already put on your server. n thumbURL: This read-only property formats the thumbScript value with the rootURL value, the thumbHeight value for the height= variable for the resize.php script, and the img= variable required by the resize.php script. The actual image name is appended to thumbURL in a later function. The String value for this property is stored in the private variable _thumbScript. 2. Save the Gallery.as file.
1061
33
Part VIII
Applying ActionScript
Any property that is preceded by an [Inspectable] tag is available in the Parameters tab of the Component Inspector panel for the Gallery component. You won’t see such properties appear unless you specify the AS3 class name in the Component Definition dialog box, which we discuss later in this chapter.
NOTE
Also, while the use of the underscore ( _ ) for private variable names used within a class is a common practice, you can name your private variables with your own custom naming convention.
LISTING 33.3
The Data Properties of the Gallery Class package com.themakers.portfolio { import import import import import import import import import import import import import import import import
flash.display.Bitmap; flash.display.BitmapData; flash.display.Sprite; flash.text.TextField; flash.events.ContextMenuEvent; flash.events.Event; flash.events.MouseEvent; flash.filters.BevelFilter; flash.filters.BlurFilter; flash.net.FileReference; flash.net.URLRequest; flash.ui.ContextMenu; flash.ui.ContextMenuItem; fl.containers.ScrollPane; fl.containers.UILoader; flash.events.ProgressEvent;
public class Gallery extends Sprite { public var _scrollPane:ScrollPane; public var _loader:UILoader; public var _captionField:TextField; private private private private
var var var var
_data:Array; _rootURL:String; _thumbHeight:Number; _thumbScript:String;
function Gallery(){ init(); }
1062
Building an Image Gallery Component
public function set items(val:Array):void { _data = val; } public function get items():Array { return _data; } [Inspectable(defaultValue=””,name=”Server Host”)] public function set rootURL(path:String):void { _rootURL = path; } public function get rootURL():String { return _rootURL != null ? _rootURL : “”; } [Inspectable(defaultValue=50)] public function set thumbHeight(val:Number):void { _thumbHeight = val; } public function get thumbHeight():Number { return _thumbHeight; } [Inspectable(defaultValue=”resize.php”)] public function set thumbScript(path:String):void { _thumbScript = path; } public function get thumbScript():String { return _thumbScript; } public function get thumbURL():String { return rootURL +thumbScript + “?height=” + thumbHeight + “&img=”; } private function init():void { trace(“Gallery.init >”); } } }
1063
33
Part VIII
Applying ActionScript
Architecting the Thumbnail class Just as the UILoader and ScrollPane components contain their own classes to perform their tasks, the Gallery class shouldn’t do all the work needed to load images, display them as thumbnails, and display an enlarged view of a clicked image. You could create a Gallery class that handled all the necessary tasks, but a more efficient (and comprehensible) approach would be to leave core functionality to the Gallery class and delegate other tasks to related classes. One such feature is the thumbnail functionality. Don’t misunderstand this point — the Gallery class could create and manage all the properties, methods, and events of each thumbnail. However, we can keep our Gallery class more compact and manageable if we create a separate class to handle thumbnail features. In this section, you create a class named Thumbnail, which has the following responsibilities: n Load a thumbnail image. n Track whether the thumbnail is the current thumbnail selected or clicked by the user. n Display rollover, rollout, and clicked states for each thumbnail. You add more features that enhance these core responsibilities later in this chapter. For now, let’s get the core responsibility accomplished. To load a thumbnail image: 1. In Flash CS4, create a new ActionScript file. Save this file in the src/com/ themakers/portfolio folder as Thumbnail.as. 2. Type the code shown in Listing 33.4, or copy and paste the code from the Listing33-4.as file from the ch33 folder of this book’s CD-ROM. This code creates a class named Thumbnail which extends the Sprite class.
The constructor function creates a new instance of the Loader class assigned to the loader property of the Thumbnail class. The onThumbInit function is added as a listener of the Event.INIT on the contentLoaderInfo property of the Loader instance. This event is broadcast whenever an asset is finished loading and initialized within a Loader instance. The buttonMode property of the Sprite class is set to true, enabling the hand cursor for button-related events. (You add these events later in the chapter.) Because the Thumbnail class inherits — or extends — the Sprite class, any property of the Sprite class can be set within the Thumbnail class. To learn more about the Loader class, review Chapter 28, “Sharing and Loading Assets.” The Loader class is an intrinsic class of ActionScript 3.0. Don’t confuse the Loader class with the UILoader component. The UILoader component is part of the fl.containers package, which adds several kilobytes to the final .swf file.
CROSS-REF
A public method named load is created, which accepts a URLRequest instance as its parameter. The request is passed on to the load() method of the Loader instance created in the constructor function.
1064
Building an Image Gallery Component
A private method named onThumbInit is also defined, which is invoked by the Event.INIT event of the Loader instance when a thumbnail finishes loading. Here, something incredibly special occurs with ActionScript 3.0 event handling — event bubbling! The dispatchEvent() method of the EventDispatcher class, which is the base class for many intrinsic classes including the Sprite class, creates a new Event instance by using the same Event.INIT constant as the Loader class. The event bubbling functionality is enabled by adding the true parameter as the second parameter of the new Event constructor. So what does event bubbling do? Put simply, an event that is “bubbled” is passed on to the parent DisplayObject of the child emitting the event. Ok, so what does that mean? It means that we can listen for the Event.INIT event from the outer container, such as the ScrollPane’s content instance, instead of adding event listeners on each and every Thumbnail instance. Later in this chapter, you’ll see where this feature comes into play. 3. Save the Thumbnail.as file. You’re now ready to create Thumbnail instances in the Gallery class! You might be wondering why you don’t need to bind the Thumbnail class to a MovieClip symbol back in the main_starter.fla Flash file. Because no authortime assets are needed for the Thumbnail class — everything happens in code — you don’t need to create a symbol in the Flash authoring document.
TIP
LISTING 33.4
The First Draft of the Thumbnail Class package com.themakers.portfolio { import import import import
flash.display.Loader; flash.display.Sprite; flash.events.Event; flash.net.URLRequest;
public class Thumbnail extends Sprite { public var id:int; private var loader:Loader; function Thumbnail(){ super(); loader = new Loader(); continued
1065
33
Part VIII
Applying ActionScript
LISTING 33.4
(continued)
loader.contentLoaderInfo.addEventListener(Event.INIT, onThumbInit); addChild(loader); buttonMode = true; } public function load(request:URLRequest):void { loader.load(request); } private function onThumbInit(evt:Event):void { dispatchEvent(new Event(Event.INIT, true)); } } }
Creating thumbnail holders in the Gallery class After you create the data properties for the Gallery class and set up the beginnings of the Thumbnail class, you’re ready to add the code that makes new Sprite holders within the nested ScrollPane instance, _scrollPane, of the Gallery symbol. 1. In the Gallery.as file, add the bold code shown in Listing 33.5. (Note that the ; character denotes a continuation of the same line of code.) The modifications and additions are as follows. The functions are described in the order that they are invoked in the class.
n init: The init function now sets a private variable named _thumbSpacing. This variable stores the number of pixels to insert between thumbnail images. You can change this number to increase or decrease the horizontal gap between thumbnails. As you see in the buildHolders function, you need to create new Sprite instances within the ScrollPane instance — you can’t add content within the ScrollPane instance without first setting the source property of the ScrollPane instance. In the init function, a new Sprite instance is created and set to the source property of the instance. n buildHolders: This function goes through the items property (which contains a list of all the JPEG file information) and builds nested Thumbnail instances within the ScrollPane instance’s content child. Each object in the items array contains a src property (mapped from the XML generated by the files.php script), which is used as the path variable value to format the URL for the resize.php script. Note that the Thumbnail class is now added to the import list at the top of the class (import com.themakers.portfolio.Thumbnail;).
1066
Building an Image Gallery Component
n calcThumbW: This function is used within the buildHolders() function to determine how wide a thumbnail image should be based on the aspect ratio of the original image. The width and height properties of the JPEG file are retrieved from nested objects within the items array. You haven’t actually loaded any data into the Gallery instance back in the main_ starter.fla file. In the next few steps, you learn how to load the XML data and format it as a data provider for the items property.
NOTE
n load: This public function initiates the thumbnail creation and loading process. This is the only method that needs to be called outside of the class. The properties added to the Gallery class in Listing 33.3 are not displayed in the printed listing of Listing 33.5, but the complete code is available in the Listing33-5.as file in the ch33 folder of this book’s CD-ROM.
NOTE
2. Save the Gallery.as file. 3. Switch over to the main_starter.fla document. Now you’re ready to load XML data from the files.php script on your server. 4. Create a new layer named actions, and place it at the top of the layer stack. Select frame 1 of the actions layer, and open the Actions panel (F9/Option+F9). Add the code shown in Listing 33.6.
This code reserves two variables names, imageData and imageXML, to load the external XML data for the gallery images. The host variable should be set to the domain name of your server. Do not use the localhost value unless you are testing against a server running on your computer. When you’re ready to deploy the final version of the Flash movie, you can set host to an empty string or to the folder path leading to the PHP script files. Also, if you have difficulties testing against your own PHP server, you can use http:// www.flash support.com/fb/as3/gallery/ as the value for the host variable to test your Flash movie.
NOTE
The init() function uses the URLLoader.addEventListener() method to delegate the Event.COMPLETE event of the imageData instance to the onFileData() function. When the XML data has loaded from the PHP script, the onFileData() function is invoked. The host value is appended to the files.php?dir=images/ string in the load() method of the imageData instance. The onFileData() function cycles through the returned XML data, which resembles that shown earlier in Listing 33.1. The for each() loop goes through each node (imageXML.img) and maps each attribute to a property of the same name on an object (item) that is passed to the items array. After each node has been processed, the items array is used for the items property of the Gallery instance, gallery. (Remember, earlier in this chapter, you placed an instance of the Gallery symbol on the Stage and named it gallery.)
1067
33
Part VIII
Applying ActionScript
The rootURL, thumbScript, and thumbHeight properties of the Gallery instance are also set in the onFileData() function. After these properties have been set, the load() function is invoked, starting the process of loading the thumbnail images. 5. Save the main_starter.fla document and test the movie (Ctrl+Enter/Ô+Enter). If the PHP script files are uploaded and correctly specified in the frame 1 script, the thumbnail images load into the ScrollPane instance of the Gallery component, as shown in Figure 33.4. Note that the scroll bar for the ScrollPane instance does not automatically appear — you fix that in a later section.
FIGURE 33.4 The basic thumbnails loading into the Gallery component
LISTING 33.5
The Thumbnail Creation Process package com.themakers.portfolio{ import import import import import import import
1068
flash.display.Bitmap; flash.display.BitmapData; flash.display.Sprite; flash.text.TextField; flash.events.ContextMenuEvent; flash.events.Event; flash.events.MouseEvent;
Building an Image Gallery Component
import import import import import import import import import import
flash.filters.BevelFilter; flash.filters.BlurFilter; flash.net.FileReference; flash.net.URLRequest; flash.ui.ContextMenu; flash.ui.ContextMenuItem; fl.containers.ScrollPane; fl.containers.UILoader; flash.events.ProgressEvent; com.themakers.portfolio.Thumbnail;
public class Gallery extends Sprite { public var _scrollPane:ScrollPane; public var _loader:UILoader; public var _captionField:TextField; private private private private private
var var var var var
_data:Array; _rootURL:String; _thumbHeight:Number; _thumbScript:String; _thumbSpacing:Number;
function Gallery() { init(); } [Public properties omitted from this listing...] public function load():void { buildHolders(); } private function buildHolders():void { var holder:Sprite = _scrollPane.content as Sprite; var files:Array = items; var w:Number = 0; for(var i:int = 0; i < files.length; i++){ var item:Object = files[i]; var th:Thumbnail = new Thumbnail(); th.id = i; th.x = (i == 0) ? 0 : (holder.getChildAt(i-1) ; as Thumbnail).x + calcThumbW(files[i-1]) + _thumbSpacing; var path:String = thumbURL + escape(item.src); continued
1069
33
Part VIII
Applying ActionScript
LISTING 33.5
(continued)
th.load(new URLRequest(path)); holder.addChild(th); } } private function calcThumbW(file:Object):Number { var w:Number = file.width; var h:Number = file.height; var factor:Number = thumbHeight/h; return w*factor; } private function init():void { trace(“Gallery.init >”); _thumbSpacing = 1; var holder:Sprite = new Sprite(); _scrollPane.source = holder; } } }
LISTING 33.6
Loading the XML Data var imageData:URLLoader; var imageXML:XML; var host:String = “http://localhost/”; init(); function init():void { imageData = new URLLoader(); imageData.addEventListener(Event.COMPLETE, onFileData); var url:String = host + “files.php?dir=images/”; imageData.load(new URLRequest(url)); } function onFileData(evt:Event):void { imageXML = new XML(evt.currentTarget.data); var items:Array = new Array();
1070
Building an Image Gallery Component
for each(var prop:XML in imageXML.img){ var item:Object = { src: prop.@src, width: Number(prop.@width), height: Number(prop.@height), caption: prop.@caption, filename: prop.@filename }; items.push(item); } gallery.items = items; gallery.rootURL = host; gallery.thumbScript = “resize.php”; gallery.thumbHeight = 50; gallery.load(); }
ON the CD-ROM
You can find this version of the main_starter.fla file as main_101.fla in the ch33/in_process folder on this book’s CD-ROM.
Phase 3: Displaying the Full-Size JPEG Image Because the XML data provided by the files.php script completely describes each JPEG image in the chosen server folder, your work with the main_starter.fla document is finished. You complete the remaining changes within the Gallery class file.
Loading the full-size image After you have the thumbnail JPEG images loading from the resize.php script, you’re ready to add more functionality to each Thumbnail instance containing a JPEG thumbnail. The th instance created in the for() loop of the buildHolders() function is the primary instance to target for adding button behaviors. You also need to track which thumbnail is currently selected. Just as the List and ComboBox components have a selectedIndex property indicating which entry in the list is active, the Gallery component needs a selectedIndex property to indicate which thumbnail the user has clicked. 1. Go back to the Gallery.as file and add the bold code shown in Listing 33.7. This code has the following changes:
1071
33
Part VIII
Applying ActionScript
n buildHolders: This function now invokes the addEventListener() method for each th instance holding a JPEG thumbnail image. The MouseEvent.CLICK event is broadcast to the onThumbClick() function of the Gallery class. n onThumbClick: This function is invoked whenever the user clicks a thumbnail image in the ScrollPane instance. When a thumbnail is clicked, the selected Index property is set to that Thumbnail instance’s id value. Remember, the for() loop of the buildHolder() function assigns an id value to each th instance. The id value matches the index of the corresponding JPEG data in the items array. n loadImage: This function does the work of changing the source property of the UILoader instance, _loader, to the full-size JPEG image URL. The selected Index value is used to look up the JPEG file data from the items array. The src property, as built by the script in Listing 33.7, contains the URL to the JPEG image. This value is appended to the rootURL value and then set as the new source property value. The loadImage() function, by design, is invoked only by the selected Index setter function. n selectedIndex: This pair of setter/getter functions creates a new property named selectedIndex. This property tracks which index of the items array is currently selected. Whenever the user clicks a thumbnail button, the selectedIndex value is updated and the loadImage() function is invoked. 2. Save the Gallery.as file. 3. Go back to the main_starter.fla document and test it (Ctrl+Enter/Ô+Enter). After the thumbnails load, click the first thumbnail image. The full-size JPEG then loads into the UILoader component of the Gallery component, as shown in Figure 33.5.
FIGURE 33.5 The full-size JPEG image for the first thumbnail
1072
Building an Image Gallery Component
LISTING 33.7
Loading the Large Image from a Clicked Thumbnail package com.themakers.portfolio{ import import import import import import import import import import import import import import import import import
flash.display.Bitmap; flash.display.BitmapData; flash.display.Sprite; flash.text.TextField; flash.events.ContextMenuEvent; flash.events.Event; flash.events.MouseEvent; flash.filters.BevelFilter; flash.filters.BlurFilter; flash.net.FileReference; flash.net.URLRequest; flash.ui.ContextMenu; flash.ui.ContextMenuItem; fl.containers.ScrollPane; fl.containers.UILoader; flash.events.ProgressEvent; com.themakers.portfolio.Thumbnail;
public class Gallery extends Sprite { public var _scrollPane:ScrollPane; public var _loader:UILoader; public var _captionField:TextField; private private private private private private
var var var var var var
_data:Array; _rootURL:String; _selectedIndex:int; _thumbHeight:Number; _thumbScript:String; _thumbSpacing:Number;
function Gallery() { init(); } [Other public properties omitted from this listing...] public function set selectedIndex(idx:int):void { _selectedIndex = idx; loadImage(); } continued
1073
33
Part VIII
Applying ActionScript
LISTING 33.7
(continued)
public function get selectedIndex():int { return _selectedIndex; } public function load():void { buildHolders(); } private function buildHolders():void { var holder:Sprite = _scrollPane.content as Sprite; var files:Array = items; var w:Number = 0; for(var i:int = 0; i < files.length; i++){ var item:Object = files[i]; var th:Thumbnail = new Thumbnail(); th.id = i; th.x = (i == 0) ? 0 : (holder.getChildAt(i-1) ; as Thumbnail).x + calcThumbW(files[i-1]) + _thumbSpacing; th.addEventListener(MouseEvent.CLICK, onThumbClick); var path:String = thumbURL + escape(item.src); th.load(new URLRequest(path)); holder.addChild(th); } } private function calcThumbW(file:Object):Number { [No changes to this function] } private function init():void { [No changes to this function] } private function loadImage():void { var idx:int = selectedIndex; var item:Object = items[idx]; _loader.source = rootURL + item.src; } private function onThumbClick(evt:MouseEvent):void { var clickedThumb:Thumbnail = evt.currentTarget as Thumbnail; selectedIndex = clickedThumb.id; } } }
1074
Building an Image Gallery Component
Updating the scroll bar and auto-loading the first image As Figures 33.4 and 33.5 illustrate, the scroll bar of the nested ScrollPane instance (_scrollPane) is not visible as more thumbnails load into the instance. The ScrollPane instance needs to be told when to redraw its UI elements — the ScrollPane component does not automatically detect when more content has been added beyond its visible frame. 1. Go to the Gallery.as file and add the functions shown in Listing 33.8. Place these functions alphabetically within the list of existing private functions in the class. This listing contains updated code for the buildHolders function and two new functions:
n onThumbInit: This function is an event listener for the Event.INIT event now added in the buildHolders() function. Whenever a thumbnail image has finished loading, the onThumbInit() function is automatically invoked by the content instance within the ScrollPane instance. If you recall from our past work in the Thumbnail class, the Event.INIT event is allowed to bubble to any parent container of a Thumbnail instance. A reference to the Thumbnail instance is passed to the function, where the id value assigned to the Thumbnail instance is accessed. When the first thumbnail in the series of images within the ScrollPane instance loads, the selectedIndex property is set to 0, which invokes all the code in the public function set selectedIndex() area of the class file. This process sets the loading of the first full-size JPEG image into action. Whenever a thumbnail is loaded into the ScrollPane instance, the updateScroller() function is invoked. n updateScroller: This function fires one action: _scrollPane.refresh Pane();. This action forces the ScrollPane instance to reexamine its contents and determine if a vertical and/or horizontal scroll bar is necessary.
NOTE
The Listing33-8.as file in the ch33 folder of this book’s CD-ROM shows the new code within the entire Gallery class file.
2. Save the Gallery.as file. 3. Go back to the main_starter.fla document and test it (Ctrl+Enter/Ô+Enter). When all the thumbnails have loaded, the horizontal scroll bar for the ScrollPane instance should appear, enabling you to scroll to more thumbnail images. See Figure 33.6.
1075
33
Part VIII
Applying ActionScript
FIGURE 33.6 The updated ScrollPane instance
LISTING 33.8
The buildHolders, onThumbInit, and updateScroller Functions private function buildHolders():void { var holder:Sprite = _scrollPane.content as Sprite; var files:Array = items; var w:Number = 0; holder.addEventListener(Event.INIT, onThumbInit); for(var i:int = 0; i < files.length; i++){ var item:Object = files[i]; var th:Thumbnail = new Thumbnail(); th.id = i; th.x = (i == 0) ? 0 : (holder.getChildAt(i-1) as ; Thumbnail).x + calcThumbW(files[i-1]) + _thumbSpacing; th.addEventListener(MouseEvent.CLICK, onThumbClick); var path:String = thumbURL + escape(item.src); th.load(new URLRequest(path)); holder.addChild(th); }
1076
Building an Image Gallery Component
} private function onThumbInit(evt:Event):void { var th:Thumbnail = evt.target as Thumbnail; var id:int = th.id; if(id == 0) selectedIndex = 0; updateScroller(); } private function updateScroller():void { _scrollPane.refreshPane(); }
Phase 4: Enhancing the Thumbnail and Image States Right now, you have a Gallery component that can load clickable thumbnails that load full-size JPEG images. Although this functionality is critical to the success of the Gallery component, the same functionality could be accomplished with less effort in a regular HTML page. Let’s add some features that are truly within the domain of Flash technology.
Tracking the selected thumbnail In this section, you learn how to keep track of a selected thumbnail image. To enable such functionality, you need to modify the Gallery and Thumbnail classes. The Thumbnail class needs a property that can determine whether it was the last thumbnail clicked. We name this property active. When a thumbnail is clicked, it should know that it has been clicked and its active property should be set to true. Similarly, the Gallery class should know which Thumbnail instance is active so that when a new Thumbnail instance is clicked, the former Thumbnail instance’s active property can be set to false before setting the newly clicked instance’s active property to true. In the following steps, you add the active property to the Thumbnail class and track it in the Gallery class. Note that there are no visible changes to the images or user interface just yet — you’ll see new visual states in the next section. 1. Go back to the Thumbnail.as file and add the bold code shown in Listing 33.9. This code adds new getter/setter functions to add a new property named active, whose value is stored in a private variable named _active. 2. Save the Thumbnail.as file.
1077
33
Part VIII
Applying ActionScript
3. Switch over to the Gallery.as file and add the bold code shown in Listing 33.10. This code adds new getter/setter functions to add a new property named thumbnail, whose value is stored in a private variable named _thumb. When a new Thumbnail instance is set as the value of the thumbnail property, any previous Thumbnail instance’s active property is set to false and the new instance’s active property is set to true. 4. Save the Gallery.as file.
LISTING 33.9
The Active Property of the Thumbnail Class package com.themakers.portfolio { import import import import
flash.display.Loader; flash.display.Sprite; flash.events.Event; flash.net.URLRequest;
public class Thumbnail extends Sprite { public var id:int; private var _active:Boolean; private var loader:Loader; function Thumbnail(){ [No changes to this function] } public function set active(val:Boolean):void { _active = val; } public function get active():Boolean { return _active; } public function load(request:URLRequest):void { loader.load(request); } private function onThumbInit(evt:Event):void { dispatchEvent(new Event(Event.INIT, true)); } } }
1078
Building an Image Gallery Component
LISTING 33.10
The Thumbnail Property and Updated Gallery Class package com.themakers.portfolio{ import import import import import import import import import import import import import import import import import
flash.display.Bitmap; flash.display.BitmapData; flash.display.Sprite; flash.text.TextField; flash.events.ContextMenuEvent; flash.events.Event; flash.events.MouseEvent; flash.filters.BevelFilter; flash.filters.BlurFilter; flash.net.FileReference; flash.net.URLRequest; flash.ui.ContextMenu; flash.ui.ContextMenuItem; fl.containers.ScrollPane; fl.containers.UILoader; flash.events.ProgressEvent; com.themakers.portfolio.Thumbnail;
public class Gallery extends Sprite { public var _scrollPane:ScrollPane; public var _loader:UILoader; public var _captionField:TextField; private private private private private private private
var var var var var var var
_data:Array; _rootURL:String; _selectedIndex:int; _thumb:Thumbnail; _thumbHeight:Number; _thumbScript:String; _thumbSpacing:Number;
function Gallery() { init(); } [Other public properties omitted from this listing...] public function set thumbnail(val:Thumbnail):void { if(_thumb != null) _thumb.active = false; _thumb = val; continued
1079
33
Part VIII
Applying ActionScript
LISTING 33.10
(continued)
_thumb.active = true; } public function get thumbnail():Thumbnail { return _thumb; } public function load():void { buildHolders(); } private function buildHolders():void { var holder:Sprite = _scrollPane.content as Sprite; var files:Array = items; var w:Number = 0; holder.addEventListener(Event.INIT, onThumbInit); for(var i:int = 0; i < files.length; i++){ var item:Object = files[i]; var th:Thumbnail = new Thumbnail(); th.id = i; th.x = (i == 0) ? 0 : (holder.getChildAt(i-1) as ; Thumbnail).x + calcThumbW(files[i-1]) + _thumbSpacing; th.addEventListener(MouseEvent.CLICK, onThumbClick); if(i == 0) thumbnail = th; var path:String = thumbURL + escape(item.src); th.load(new URLRequest(path)); holder.addChild(th); } } private function calcThumbW(file:Object):Number { [No changes to this function] } private function init():void { [No changes to this function] } private function loadImage():void { [No changes to this function] } private function onThumbClick(evt:MouseEvent):void { var clickedThumb:Thumbnail = evt.currentTarget as Thumbnail; thumbnail = clickedThumb;
1080
Building an Image Gallery Component
selectedIndex = clickedThumb.id; } private function onThumbInit(evt:Event):void { [No changes to this function] } private function updateScroller():void { _scrollPane.refreshPane(); } } }
Framing the selected thumbnail with the BevelFilter class In this section, you learn how to add a bevel filter to the selected thumbnail image. The BevelFilter class is just one of several graphics filters that can be applied at runtime to MovieClip, TextField, and Sprite instances in Flash movies. 1. Go back to the Thumbnail.as file and add the code shown in Listing 33.11. This code adds two new functions, and an updated active setter function:
n active setter function: When the active property of a Thumbnail instance is set, the Boolean value (true or false) determines how the Thumbnail instance displays itself. When set to true, the frame() method of the class is called. When set to false, the dim() method of the class is invoked. n frame: This function creates a new BevelFilter instance named bf. The bf instance is assigned to the filters array of the instance, and the alpha of the clip is set to 100% (1.0). We use the default values of the BevelFilter class. If you search the Flash CS4 Help pages for “BevelFilter class,” you can find more information on changing the look and feel of the filter with the thumbnail images, using BevelFilter properties such as distance and angle.
TIP
n dim: This function removes any filters applied to the instance, and sets the alpha of the thumbnail to 75% (0.75). 2. Save the Thumbnail.as file. 3. Go back to the main_starter.fla document and test it (Ctrl+Enter/Ô+Enter). When the movie loads, the first thumbnail appears with a bevel border. If you click another thumbnail, the previously selected thumbnail’s bevel is removed and the alpha is reduced, as shown in Figure 33.7.
1081
33
Part VIII
Applying ActionScript
FIGURE 33.7 The BevelFilter instance applied to the thumbnail image
LISTING 33.11
Framing the Selected Thumbnail package com.themakers.portfolio { import import import import import
flash.display.Loader; flash.display.Sprite; flash.events.Event; flash.filters.BevelFilter; flash.net.URLRequest;
public class Thumbnail extends Sprite { public var id:int; private var _active:Boolean; private var loader:Loader; function Thumbnail(){ [No changes to this function] } public function set active(val:Boolean):void { if(val) frame();
1082
Building an Image Gallery Component
else dim(); _active = val; } public function get active():Boolean { return _active; } public function load(request:URLRequest):void { loader.load(request); } private function dim():void { this.filters = []; this.alpha = 0.75; } private function frame():void { var bf:BevelFilter = new BevelFilter(); this.filters = [bf]; this.alpha = 1.0; } private function onThumbInit(evt:Event):void { dispatchEvent(new Event(Event.INIT, true)); } } }
Creating a loading transition with the BitmapData and BlurFilter classes Let’s continue the fun with Flash filters! In this section, you learn how to use the BitmapData and Bitmap classes to make a copy of the thumbnail image over the UILoader component area. The thumbnail, of course, is not as large as the full-size JPEG image. As such, the thumbnail image is stretched and pixilated when it’s set to the same width and height of the full-size image. You use the BlurFilter class to smooth the thumbnail’s pixilation. The filter’s strength is inversely proportional to the loaded percent of the full-size JPEG image. As the full-size JPEG image loads into the UILoader component, the intensity of the BlurFilter instance is gradually diminished. Before you can alter the Gallery class to make a copy of the JPEG thumbnail image, you need to add a property to the Thumbnail class to retrieve an unaltered version of the thumbnail image. Remember, the active thumbnail has a bevel filter applied. For the blur transition effect, the bevel filter should not be included.
1083
33
Part VIII
Applying ActionScript
1. Open the Thumbnail.as file and add the bold code shown in Listing 33.12. The new imageData property is declared with a getter function, retrieving the content property of the internal Loader instance within the Thumbnail instance. Because the Loader instance is being used to load bitmap graphic files, the content property is of the Bitmap type. To retrieve the actual pixel data of this Bitmap instance, the bitmapData property is used and returned whenever the Thumbnail.imageData property is retrieved. Note that the Bitmap and BitmapData classes are added to the import list at the top of the class.
TIP
You don’t always need to declare a setter function for class properties. If you only need to retrieve — and not set — data from a class, then declare only a getter function.
Now you’re ready to copy and blur enlarged copies of the Thumbnail instances. 2. Go back to the Gallery.as file and add the bold code shown in Listing 33.13. This code modifies existing functions and adds a few new ones:
n init: This function uses a new private variable, _blurStrength, which indicates the maximum blur applied to the copied thumbnail when the copy is made. This function is also modified to add two event listeners to the UILoader component, _ loader. The ProgressEvent.PROGRESS event is broadcasted from the UILoader component as new bytes of a loaded full-size JPEG image arrive into the Flash movie. This event is captured by the onImgProgress function. The Event.COMPLETE event is broadcasted by the UILoader component when the full-size JPEG image has fully loaded into the Flash movie. This event is captured by the onImgComplete function. n overlayThumb: This function creates a bitmap copy of the selected thumbnail, scales the copy to fit within the dimensions of the UILoader component, and sets the initial blur of the scaled copy to a maximum intensity. The selectedIndex property invokes the overlayThumb function when a new thumbnail is clicked. Here, the BitmapData and Bitmap classes create the copy of the loaded thumbnail JPEG image. The new bitmap is attached to a new Sprite holder, used as the value of a new _overlay property of the Gallery class. The _overlay instance is then resized, using the same procedure that the UILoader component uses to fit loaded images within its display area. (A new private variable named _overlay is declared at the top of the Gallery class to store the Sprite instance.) n blurOverlay: This function creates the BlurFilter instance responsible for blurring the copied thumbnail image. The function requires one parameter: the percent loaded of the full-size JPEG image. If the loading process has just started, the percent loaded is equal to 0. This value is remapped to a blur intensity value (blurVal), as indicated by the _blurStrength variable set in the init() function. As more bytes of the JPEG image load into the movie, the blurVal amount is reduced. The BlurFilter instance is applied to the filters array of the _overlay instance.
1084
Building an Image Gallery Component
n onImgProgress: This handler is invoked whenever the UILoader component broadcasts a ProgressEvent.PROGRESS event. When this event occurs, the loaded percent of the JPEG is retrieved with the percentLoaded property of the UILoader component and passed to the blurOverlay function. n onImgComplete: When the UILoader component broadcasts the Event. COMPLETE event, the onImgComplete function is invoked. This event signals that the full-size JPEG image has loaded completely into the Flash movie. At this point, the _overlay instance can be removed to reveal the full-size JPEG below it. n selectedIndex: The overlayThumb function is added to the setter function for the selectedIndex property. Whenever the user clicks a new thumbnail image, the process of copying, scaling, and blurring the thumbnail starts. 3. Save the Gallery.as file. 4. Go back to the main_starter.fla document and test it (Ctrl+Enter/Ô+Enter). When you click a thumbnail image, a copy of the thumbnail is created, scaled, blurred, and positioned above the UILoader component. The blur intensity is minimized as the full-size JPEG loads into the movie. Figure 33.8 shows a snapshot of this animated transition.
FIGURE 33.8 The blurred copy of the thumbnail image
1085
33
Part VIII
Applying ActionScript
LISTING 33.12
Declaring an imageData Property for the Thumbnail Class package com.themakers.portfolio { import import import import import import import
flash.display.Bitmap; flash.display.BitmapData; flash.display.Loader; flash.display.Sprite; flash.events.Event; flash.filters.BevelFilter; flash.net.URLRequest;
public class Thumbnail extends Sprite { public var id:int; private var _active:Boolean; private var loader:Loader; function Thumbnail(){ [No changes to this function] } public function set active(val:Boolean):void { [No changes to this function] } public function get active():Boolean { return _active; } public function get imageData():BitmapData { if(loader.content != null){ var content:Bitmap = loader.content as Bitmap; var bd:BitmapData = content.bitmapData; return bd; } return null; } public function load(request:URLRequest):void { loader.load(request); }
1086
Building an Image Gallery Component
private function dim():void { [No changes to this function] } private function frame():void { [No changes to this function] } private function onThumbInit(evt:Event):void { dispatchEvent(new Event(Event.INIT, true)); } } }
LISTING 33.13
Enabling the Blur Effect on an Enlarged Thumbnail Copy package com.themakers.portfolio{ import import import import import import import import import import import import import import import import import
flash.display.Bitmap; flash.display.BitmapData; flash.display.Sprite; flash.text.TextField; flash.events.ContextMenuEvent; flash.events.Event; flash.events.MouseEvent; flash.filters.BevelFilter; flash.filters.BlurFilter; flash.net.FileReference; flash.net.URLRequest; flash.ui.ContextMenu; flash.ui.ContextMenuItem; fl.containers.ScrollPane; fl.containers.UILoader; flash.events.ProgressEvent; com.themakers.portfolio.Thumbnail;
public class Gallery extends Sprite { public var _scrollPane:ScrollPane; public var _loader:UILoader; continued
1087
33
Part VIII
Applying ActionScript
LISTING 33.13
(continued)
public var _captionField:TextField; private private private private private private private private private
var var var var var var var var var
_blurStrength:Number; _data:Array; _overlay:Sprite; _rootURL:String; _selectedIndex:int; _thumb:Thumbnail; _thumbHeight:Number; _thumbScript:String; _thumbSpacing:Number;
function Gallery() { init(); } [Other public properties omitted from this listing...] public function set selectedIndex(idx:int):void { _selectedIndex = idx; overlayThumb(); loadImage(); } public function load():void { buildHolders(); } private function blurOverlay(pl:Number):void { var n:Number = (pl*(_blurStrength/10))/10; var blurVal:Number = _blurStrength - n; var bf:BlurFilter = new BlurFilter(blurVal, blurVal, 3); _overlay.filters = [bf]; } private function buildHolders():void { var holder:Sprite = _scrollPane.content as Sprite; var files:Array = items; var w:Number = 0; holder.addEventListener(Event.INIT, onThumbInit); for(var i:int = 0; i < files.length; i++){ var item:Object = files[i]; var th:Thumbnail = new Thumbnail(); th.id = i; th.x = (i == 0) ? 0 : (holder.getChildAt(i-1) as ; Thumbnail).x + calcThumbW(files[i-1]) + _thumbSpacing;
1088
Building an Image Gallery Component
th.addEventListener(MouseEvent.CLICK, onThumbClick); if(i == 0) thumbnail = th; var path:String = thumbURL + escape(item.src); th.load(new URLRequest(path)); holder.addChild(th); } } private function calcThumbW(file:Object):Number { [No changes to this function] } private function init():void { trace(“Gallery.init >”); _thumbSpacing = 1; _blurStrength = 20; _loader.addEventListener(ProgressEvent.PROGRESS, onImgProgress); _loader.addEventListener(Event.COMPLETE, onImgComplete); var holder:Sprite = new Sprite(); _scrollPane.source = holder; } private function loadImage():void { [No changes to this function] } private function onImgComplete(evt:Event):void { removeChild(_overlay); } private function onImgProgress(evt:ProgressEvent):void { var loader:UILoader = evt.currentTarget as UILoader; blurOverlay(loader.percentLoaded); } private function onThumbClick(evt:MouseEvent):void { [No changes to this function] } private function onThumbInit(evt:Event):void { [No changes to this function] } private function overlayThumb():void { var th:Thumbnail = thumbnail; var thW:Number = th.width; continued
1089
33
Part VIII
Applying ActionScript
LISTING 33.13
(continued)
var thH:Number = th.height; var bm:Bitmap = new Bitmap(th.imageData); _overlay = new Sprite(); _overlay.addChild(bm); var lW:Number = _loader.width; var lH:Number = _loader.height; var factor:Number = thH >= thW ? lH/thH : lW/thW; _overlay.scaleX = _overlay.scaleY = factor; _overlay.x = _loader.x + ((lW - _overlay.width)/2); _overlay.y = _loader.y + ((lH - _overlay.height)/2); addChild(_overlay); blurOverlay(0); } private function updateScroller():void { _scrollPane.refreshPane(); } } }
Transitioning thumbnail states with the Tween and ColorMatrixFilter classes The thumbnails in the ScrollPane component can also use a scripted tween to fade to a desaturated state as the user changes the active thumbnail. In this section, you see how the Tween class can programmatically update the thumbnail images. You can create a Tween instance by using the following syntax: import fl.transitions.Tween; import fl.transitions.easing.*; var sprite:Sprite = new Sprite(); addChild(sprite); var tw:Tween = new Tween( sprite, // Target of the tween “x”, // Property to change Regular.easeOut, // Type of easing motion sprite.x, // Start value sprite.x + 100, // End value 5, // Duration of tween, in seconds true // Use seconds instead of frames );
1090
Building an Image Gallery Component
CROSS-REF
Refer to Chapter 27, “Animating with ActionScript,” for more information on the ActionScript 3.0 Tween class and its properties.
1. Go back to the Thumbnail.as file and add the code shown in Listing 33.14. This code replaces the existing dim function with a new set of actions to utilize the Tween class.
n dim: This function is invoked from the active property, just as it was in earlier sections of this project. Two new Tween instances are created for the thumbnail instance. The first Tween instance named twSaturation is responsible for modifying the saturation value of the thumbnail instance. The Regular.easeOut static class is specified as the easing class for both Tween instances. The starting value for the saturation tween is 0 (no change) and the ending value is –100 (color removed, desaturated). The duration of both tweens is two seconds. The twAlpha instance animates the current alpha of the thumbnail instance to the muted 75% used earlier. The new onTweenFinish function is added as a listener of the TweenEvent.MOTION_ FINISH event to both Tween instances; therefore, the onTweenFinish handler of the Thumbnail class is fired when the tweens finish. Because the saturation value is not a native property of the Sprite class (upon which the Thumbnail class is based), a new getter/setter property named saturation is created for the Thumbnail class. The Tween instances are added and stored as an array in a new tweens property of the Thumbnail class. This array is used to determine which tweens have finished or are still in progress. n saturation getter/setter functions: The saturation setter function is invoked whenever the saturation tween (twSaturation) updates the saturation property of the Thumbnail instance. Here, the new value created by the tween is passed to the EasyFilter.saturate() method to create a new ColorMatrixFilter instance. We discuss the EasyFilter.saturate() method in greater detail at the start of this chapter. n onTweenFinish: This handler is invoked by each Tween instance when the respective tween has completed. Each tween is removed from a tweens array stored within each Thumbnail instance. n controlTweens, clearTweens: These functions manage the playback of the Tween instances. You add more functions later in this chapter that take advantage of these functions. 2. Save the Thumbnail.as file. 3. Go back to the main_starter.fla document and test it (Ctrl+Enter/Ô+Enter). After the thumbnail images load, click a new thumbnail in the ScrollPane component. The previously selected thumbnail desaturates and fades to 75 percent opacity.
1091
33
Part VIII
Applying ActionScript
LISTING 33.14
Tweening the Thumbnail States package com.themakers.portfolio { import import import import import import import import import import import
flash.display.Bitmap; flash.display.BitmapData; flash.display.Loader; flash.display.Sprite; flash.events.Event; flash.filters.BevelFilter; flash.net.URLRequest; fl.transitions.Tween; fl.transitions.TweenEvent; fl.transitions.easing.Regular; com.themakers.effects.EasyFilter;
public class Thumbnail extends Sprite { public var id:int; private private private private
var var var var
_active:Boolean; loader:Loader; saturationValue:Number; tweens:Array;
function Thumbnail(){ super(); loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.INIT, onThumbInit); addChild(loader); tweens = new Array(); buttonMode = true; } public function set active(val:Boolean):void { [No changes to this function] } public function get active():Boolean { return _active; }
1092
Building an Image Gallery Component
public function get imageData():BitmapData { [No changes to this function] } public function set saturation(val:Number):void { filters = [EasyFilter.saturate(val)]; saturationValue = val; } public function get saturation():Number { return saturationValue; } public function load(request:URLRequest):void { loader.load(request); } private function clearTweens():void { controlTweens(“stop”); tweens = new Array(); } private function controlTweens(action:String):void { for(var i:int = 0; i < tweens.length; i++){ tweens[i][action](); } } private function dim():void { if(tweens.length > 0) clearTweens(); var twSaturation:Tween = new Tween(this, “saturation”, ; Regular.easeOut, 0, -100, 2, true); var twAlpha:Tween = new Tween(this, “alpha”, Regular.easeIn, ; this.alpha, 0.75, 2, true); twSaturation.addEventListener(TweenEvent.MOTION_FINISH, ; onTweenFinish); twAlpha.addEventListener(TweenEvent.MOTION_FINISH, onTweenFinish); tweens = [twSaturation, twAlpha]; } private function frame():void { [No changes to this function] } private function onThumbInit(evt:Event):void { dispatchEvent(new Event(Event.INIT, true)); } continued
1093
33
Part VIII
Applying ActionScript
LISTING 33.14
(continued)
private function onTweenFinish(evt:TweenEvent):void { var tw:Tween = evt.currentTarget as Tween; for(var i:int = 0; i < tweens.length; i++){ if(tweens[i] == tw) tweens.splice(i, 1); } if(tweens.length < 1) tweens = new Array(); } } }
Setting the image caption After you have the full-size JPEG image loading into the UILoader component, you’re ready to populate the _captionField TextField instance, which you copied into the Gallery symbol earlier in this chapter. The JPEG files provided in the starter files and finished files folders have had metadata added to them. The caption metadata is read by the JPEG-Meta.php script on the server and inserted into the XML data sent to the Flash movie with the files.php script. 1. Go back to the Gallery.as file and add the bold code shown in Listing 33.15. Add the new private variable _captionSpacing to the list of existing private variables at the top of the class file, modify the existing init() and loadImage() functions, and add the new displayCaption() function below the last private function in the class file.
n init: The new _captionSpacing variable stores the gap, in pixels, that should buffer the top of the _captionField instance and the bottom of the full-size JPEG image. n loadImage: After the full-size JPEG image starts to load into the UILoader component, the displayCaption() function is invoked to show the image’s caption. The caption text is stored in the caption property of the current object within the items array, as described by the XML document delivered by the files.php script. n displayCaption: This function populates the _captionField instance with the new caption text and positions the field below the lower left corner of the image. 2. Save the Gallery.as file. 3. Return to the main_starter.fla document and test it (Ctrl+Enter/Ô+Enter). When a new full-size JPEG image is loaded, its caption text (if available) appears below the image, as shown in Figure 33.9.
1094
Building an Image Gallery Component
FIGURE 33.9 The caption text below the JPEG image
LISTING 33.15
The displayCaption() Function private var _captionSpacing:Number; private function init():void { trace(“Gallery.init >”); _thumbSpacing = 1; _blurStrength = 20; _captionSpacing = 5; _loader.addEventListener(ProgressEvent.PROGRESS, onImgProgress); _loader.addEventListener(Event.COMPLETE, onImgComplete); var holder:Sprite = new Sprite(); _scrollPane.source = holder; } private function loadImage():void { var idx:int = selectedIndex; continued
1095
33
Part VIII
Applying ActionScript
LISTING 33.15
(continued)
var item:Object = items[idx]; _loader.source = rootURL + item.src; displayCaption(item.caption); } private function displayCaption(val:String):void { _captionField.text = val; _captionField._x = _overlay.x; _captionField._y = _overlay.y + _overlay.height + _captionSpacing; }
Completing the thumbnail button handlers The thumbnail functionality is nearly complete. In its current state, the thumbnail images, when clicked, remain muted — even when the user rolls over a previously selected thumbnail. In this section, you add MouseEvent.ROLL_OVER and MouseEvent.ROLL_OUT event listeners to each thumbnail instance. 1. Go back to the Thumbnail.as file and add the bold code shown in Listing 33.16. This code contains the following changes:
n Thumbnail constructor function: This function, which creates the thumbnail, is modified to assign MouseEvent.ROLL_OVER and MouseEvent.ROLL_OUT event listeners. The addEventListener() method delegates these events to the onThumbOver and onThumbOut functions of the Thumbnail class. n onThumbOver: This handler checks to see if any tweens are active on the thumbnail when the rollover event occurs. If there are any active tweens, they are paused. Any active filters applied to the instance are stored in a new property named existingProps. This property is used in onThumbOut to restore the last state of the button. Any filters on the thumbnail instance are removed, and the alpha is set to 100%. Note that these actions are applied to a thumbnail instance only if it is not the active thumbnail. n onThumbOut: This handler resumes any active tweens that may have been in progress when the user rolled over the thumbnail instance. Any filters that were applied to the instance before the rollover event occurred are also reapplied to the clip. n storeProps: When a thumbnail’s active property is set to true, the storeProps function initializes a new existingProps property with the filters that are applied to the selected thumbnail. 2. Save the Gallery.as file.
1096
Building an Image Gallery Component
3. Return to the main_starter.fla file and test it (Ctrl+Enter/Ô+Enter). After the thumbnail images load, start clicking each one. After the previously selected thumbnail fades out, roll back over the thumbnail. The original saturation and alpha of the thumbnail should appear; when you roll off the thumbnail, the desaturated view of the thumbnail returns.
That’s it with the Thumbnail class! In the remaining sections, you add extended functionality to the Gallery class.
LISTING 33.16
Enabling Mouse Events within the Thumbnail Class package com.themakers.portfolio { import import import import import import import import import import import import
flash.display.Bitmap; flash.display.BitmapData; flash.display.Loader; flash.display.Sprite; flash.events.Event; flash.events.MouseEvent; flash.filters.BevelFilter; flash.net.URLRequest; fl.transitions.Tween; fl.transitions.TweenEvent; fl.transitions.easing.Regular; com.themakers.effects.EasyFilter;
public class Thumbnail extends Sprite { public var id:int; private private private private private
var var var var var
_active:Boolean; existingProps:Object; loader:Loader; saturationValue:Number; tweens:Array;
function Thumbnail(){ super(); loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.INIT, onThumbInit); continued
1097
33
Part VIII
Applying ActionScript
LISTING 33.16
(continued)
addChild(loader); tweens = new Array(); addEventListener(MouseEvent.ROLL_OVER, onThumbOver); addEventListener(MouseEvent.ROLL_OUT, onThumbOut); buttonMode = true; } public function set active(val:Boolean):void { if(val) frame(); else dim(); storeProps(); _active = val; } [Other public properties omitted from this listing...] public function load(request:URLRequest):void { loader.load(request); } private function clearTweens():void { [No changes to this function] } private function controlTweens(action:String):void { [No changes to this function] } private function dim():void { [No changes to this function] } private function frame():void { [No changes to this function] } private function onThumbInit(evt:Event):void { dispatchEvent(new Event(Event.INIT, true)); } private function onThumbOver(evt:MouseEvent):void {
1098
Building an Image Gallery Component
if(!active){ if(tweens.length > 0) controlTweens(“stop”); storeProps(); this.filters = new Array(); this.alpha = 1.0; } } private function onThumbOut(evt:MouseEvent):void { if(tweens.length > 0 && !active){ controlTweens(“resume”); } else if(existingProps != null) { filters = existingProps.filters; alpha = existingProps.alpha; } } private function onTweenFinish(evt:TweenEvent):void { [No changes to this function] } private function storeProps():void { var existingFilters:Array = new Array(); for(var i:int = 0; i < filters.length; i++){ existingFilters.push(filters[i]); } existingProps = { filters: existingFilters, alpha: alpha}; } } }
Building a right-click download menu item for the full-size JPEG To enable the user to download the full-size JPEG image, you use the ContextMenu class to add a new custom menu item to the Flash Player’s context menu that appears when the user rightclicks (or Control+clicks on Mac) the UILoader component display area. 1. Go back to the Gallery.as file and add the bold code shown in Listing 33.17. This code creates or modifies the following functions:
n init function: This handler, which is invoked automatically when the Gallery instance loads in the Flash movie, now invokes the addContextMenu() function.
1099
33
Part VIII
Applying ActionScript
n addContextMenu: This function creates a new instance of the ContextMenu class. The built-in items of the Flash Player contextual menu (such as Zoom In, Zoom Out, and so on) are disabled for this new menu. A new custom menu item is created, named “Download this image,” retrieved from a new constant in the class, CONTEXT_ MENU_CAPTION. When the user selects this menu item, the downloadImage() function is invoked. The new menu is then assigned to the UILoader component, _loader. n downloadImage: This function uses the FileReference API to enable the user to download a file from the server. The current JPEG file URL and JPEG filename values are retrieved from the items array, and passed to the download() method of the fileRef instance. 2. Save the Gallery.as file. 3. Go back to the main_starter.fla document and test it (Ctrl+Enter/Ô+Enter). When a full-size JPEG image loads into the Flash movie, right-click (or Control+click on Mac) the JPEG image. The contextual menu displays the “Download this image” option, as shown in Figure 33.10. If you select this menu item, a Save dialog box appears, enabling you to save the JPEG file to your computer.
FIGURE 33.10 The new right-click menu item
1100
Building an Image Gallery Component
LISTING 33.17
Utilizing the FileReference API public static const CONTEXT_MENU_CAPTION:String = “Download this image”; private function addContextMenu():void { var cm:ContextMenu = new ContextMenu(); cm.hideBuiltInItems(); var mi:ContextMenuItem = new ContextMenuItem(CONTEXT_MENU_CAPTION); mi.enabled = true; mi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, downloadImage); cm.customItems.push(mi); _loader.contextMenu = cm; } private function downloadImage(evt:ContextMenuEvent):void { var fileRef:FileReference = new FileReference(); var item:Object = items[selectedIndex]; var path:String = rootURL + item.src; fileRef.download(new URLRequest(path), item.filename); } private function init():void { trace(“Gallery.init >”); _thumbSpacing = 1; _blurStrength = 20; _captionSpacing = 5; _loader.addEventListener(ProgressEvent.PROGRESS, onImgProgress); _loader.addEventListener(Event.COMPLETE, onImgComplete); var holder:Sprite = new Sprite(); _scrollPane.source = holder; addContextMenu(); }
1101
33
Part VIII
Applying ActionScript
Phase 5: Finalizing the Component You’ve completed all the scripting for the Gallery component — Congratulations! You can now deploy Flash movies with the Gallery component. In this last section, you learn how to enable inspectable properties of the Gallery class to display in the Parameters tab of the Component Inspector panel.
Copying existing component class files In order for the complete the component process for the Gallery symbol, you need to copy the ActionScript 3.0 class files for the User Interface (UI) components placed within the Gallery symbol. In this example, we use the ScrollPane and UILoader components. To keep things simple, you copy the entire fl package into your src/flash folder.
NOTE
You must complete this task in order to build component parameters for the Gallery component as discussed in the next section.
1. Browse to the following location in the C:\Program Files\Adobe folder (Windows) or [Boot disk]\Applications folder (Mac): Adobe Flash CS4\Common\Configuration\Component Source\ ; ActionScript 3.0\User Interface
2. At this location, right-click (or Control+click on Mac) the fl folder and choose Copy in the context menu. 3. Browse to the src/flash folder you created at the beginning of this chapter. Rightclick (or Control+click on Mac) an empty area in the folder window, and choose Paste. The class files for the UI components are now available to the Flash documents (.fla files) in your src/flash folder.
Adding the component definition If you open the Library panel of the main_starter.fla document, you can see that the symbol type of the Gallery symbol is a Sprite. In order to convert the component to a full-fledged component (complete with component icon!), you need to specify the Gallery class in the Component Definition dialog box. 1. With the main_starter.fla document active, open the Library panel (Ctrl+L/ Ô+L). 2. Right-click (or Control+click on Mac) the Gallery clip and choose Component Definition.
1102
Building an Image Gallery Component
3. In the Component Definition dialog box, type com.themakers.portfolio.Gallery in the Class field, as shown in Figure 33.11. Select the Require minimum player version check box, and choose Flash Player 9. Select the Require minimum ActionScript version, and choose ActionScript 3.0. If you want to choose a custom icon for your component, click the icon button below the “Description” label. Click OK.
FIGURE 33.11 The Component Definition dialog box
4. To see the inspectable parameters, repeat Step 2 to see the parameters automatically created for you by Flash CS4, as shown in Figure 33.12. 5. To see the new parameters, select the gallery instance of the Gallery component on the Stage and open the Component Inspector panel. When you select the Parameters tab, you should see the new inspectable parameters, as shown in Figure 33.13.
1103
33
Part VIII
Applying ActionScript
FIGURE 33.12 The updated Component Definition dialog box
FIGURE 33.13 The Parameters tab for the gallery instance
1104
Building an Image Gallery Component
Now, you can change the thumbnail height, server host, and thumbnail script values directly in the Properties panel.
NOTE
You still need to specify an items value for the Gallery instance in ActionScript code, and invoke the load() handler to initiate the thumbnail loading process.
Changing script paths for final deployment When you’re ready to deploy a Flash movie featuring the Gallery component, keep in mind that you may very likely need to change to the values used in the frame 1 script to initiate loading of the XML data from the files.php script. Make sure that you specify a valid server folder name (or path) as the dir value appended to the files.php filename in the URLLoader.load() handler. You may also need to update the name and path to the resize.php script in the onFileData() handler written within the frame 1 script.
WEB RESOURCE
We’d like to know what you think about this chapter. Visit www.flashsupport. com/feedback to send us your comments.
Summary n The process for planning a Flash component can require ample time to properly spec the functionality you want to build. n The Gallery component can load thumbnail versions of JPEG images on your Web server and display the full-size JPEG image when the thumbnail is clicked. n Server-side scripting can enable a wide range of functionality within your Flash movies. For the Gallery component, the PHP script files provide XML data and dynamically resized JPEG images to the Flash movie. n The JPEG-Meta.php script written by Rob Williams can retrieve JPEG metadata within your own PHP scripts. n The BitmapData class can create a copy of a bitmap image such as a loaded JPEG file. You can use this class to replicate graphics within your Flash movies. n The Flash Player filters can add more visual effects to interactive button states. n You can use the FileReference API to download and upload files, without relying on the browser to intervene.
1105
33
Appendixes
I
f you’re wondering what the CD-ROM included with this book is for and how to make the most of it, refer to Appendix A. To learn more about the Flash talent that provided expert tutorials for this edition of the book, browse their bios and visit their URLs listed in Appendix B. The experts who have provided e-mail addresses would be glad to hear from you, but we cannot guarantee that they will reply right away — they are all kind people but they are busy, too. Audio and video are both complex topics to which many other books are dedicated. We have done our best to include key information in Appendix C and Appendix D. This material will get you off on the right foot when you start creating and editing audio and video to enhance your Flash projects. Hopefully, this will help you to avoid common pitfalls and keep your media assets looking and sounding as good as your Flash content. Whether you have reached this last section by carefully reading each and every page of the book or just by flipping randomly through it, we hope that you have enjoyed it and learned something along the way. Please let us know what you thought of specific parts of the book or of the book as a whole by visiting www.flashsupport.com/feedback to fill out an online form with your comments. We appreciate your input and we always love to hear how you are using the book now and how you think it could help you in the future.
IN THIS PART Appendix A Using the CD-ROM Appendix B Guest Experts’ Information Appendix C Digital Audio Basics Appendix D Digital Video Basics
Using the CD-ROM
T
his appendix provides information on the contents of the CD-ROM that accompanies this book, and the system requirements for using the sample files and trial applications that enhance the text content of the book.
For the latest version of this appendix, including any latebreaking updates, refer to the ReadMe file located in the root directory of the CD-ROM.
NOTE
If your CD-ROM is missing from the book when you purchase it, return it to the store where you bought it and get a copy of the book that has a CD-ROM included. If you lose or damage your CD or it gets stolen, your best option is to contact the publisher (Wiley) and tell them your story — they may be able to help you, but there are no guarantees that you’ll get a free replacement. The phone and e-mail contact info for Wiley Publishing is provided at the end of this appendix. You can also find more info on what to do about missing CD-ROMs online at www.flashsupport.com/lostcd.
CAUTION
Here is what you will find on the CD-ROM: n System requirements n Source .swf and .fla files for step-by-step exercises n Reusable ActionScript Before loading the CD-ROM, make sure that your computer meets the minimum system requirements listed in this section. If your computer doesn’t match up to most of these requirements, you may have a problem using the contents of the CD-ROM.
1109
IN THIS APPENDIX Reviewing source files for step-by-step exercises Accessing custom components Troubleshooting
Part IX
Appendixes
For Windows 2000/XP/Vista: n PC with a Pentium 4 or faster processor, including Intel Centrino, Intel Xeon, or Intel Core Duo (or compatible) processor n Windows XP with Service Pack 3 or Windows Vista with Service Pack 1 (certified for 32-bit editions) n At least 1GB of total RAM installed on your computer (note that you need additional RAM to open other programs with Flash) n 2.5GB available hard-disk space (additional required during CS4 installation) n 16-bit color monitor capable of 1024 x 768 display recommended n A CD-ROM drive (DVD-ROM drive required for Creative Suite installer discs) For Macs: n PowerPC G5 or later running OS X 10.4.9 and later, running at 1 GHz or faster n 1GB of RAM n 2.5GB available hard-disk space required during installation n 1,024 x 768 monitor resolution n A CD-ROM drive (DVD-ROM drive required for Creative Suite installer discs) CS4 applications also require an Internet or phone connection for product activation. Some features of Flash CS4 require the latest version of QuickTime. During the installation of QuickTime, select the “Recommended” installation type to install the components Flash requires. To download a trial or purchase the latest version of QuickTime, go to www.apple.com/quicktimewww.quicktime.com.
NOTE
Reviewing Example .swf and .fla Files Many of the examples we discuss in the text and in step-by-step tutorials are included in the relevant chapter folder on the CD-ROM. Opening the Flash movie (.swf) is the quickest way to see how the finished example is supposed to look. The fonts should display correctly, and as long as you haven’t moved the file to a new location, any loaded assets should also work. When you open a Flash document (.fla), you may get a warning about missing fonts. This warning simply means that you do not have the same fonts installed on your machine as the original author of the file. Select a default font and you will be able to review and edit the Flash document on your machine. However, without the proper fonts installed, the layout may not appear as it was originally designed.
1110
Using the CD-ROM
Installing and Using Plug-Ins and Applications To download the Mac and Windows trial versions of Flash CS4, go to www.adobe.com/ downloads. Additional plug-ins and trial versions of applications discussed in this book can also be found online, in most cases.
Source Files and Applications The CD-ROM included with this book aids you with many examples and tutorials by providing relevant files, including the following: n Custom components for image loading and effects, scripted by Robert Reinhardt and integrated with project examples in Chapters 19, “Making Your First Flash CS4 Project,” and 33, “Building an Image Gallery Component.” n Just about every .fla and .swf file that is discussed in the book, including many shown in examples from guest experts. Shareware programs are fully functional, trial versions of copyrighted programs. If you like particular programs, register with their authors for a nominal fee and receive licenses, enhanced versions, and technical support. Freeware programs are copyrighted games, applications, and utilities that are free for personal use. Unlike shareware, these programs do not require a fee or provide technical support. GNU software is governed by its own license, which is included inside the folder of the GNU product. See the GNU license for more details. Trial, demo, or evaluation versions are usually limited either by time or functionality (such as being unable to save projects). Some trial versions are very sensitive to system date changes. If you alter your computer’s date, the programs “time out” and are no longer functional.
Troubleshooting If you have difficulty installing or using any of the materials on the companion CD-ROM, try the following: n Turn off any antivirus software that you may have running. Installers sometimes mimic virus activity and can make your computer incorrectly believe that it is being infected by a virus. (Be sure to turn the antivirus software back on later.)
1111
A
Part IX
Appendixes
n Close all running programs. The more programs you’re running, the less memory is available to other programs. Installers also typically update files and programs; if you keep other programs running, installation may not work properly. n Reference the ReadMe: Please refer to the ReadMe file located at the root of the CD-ROM for the latest product information at the time of publication.
Customer Care If you have trouble with the CD-ROM, call the Wiley Product Technical Support phone number at 800-762-2974. Outside the United States, call 1-317-572-3994. You can also contact Wiley Product Technical Support at http://support.wiley.com. John Wiley & Sons provides technical support only for installation and other general quality-control items. For technical support on the applications themselves, consult the program’s vendor or author. To place additional orders or to request information about other Wiley products, call 877-762-2974.
1112
Guest Experts’ Information Bazley, Richard Bazley Films Corsham, England, UK
IN THIS APPENDIX Contributors’ information
richard@bazleyfilms.com www.bazleyfilms.com
* Animation examples from The Journal of Edwin Carp in Part III Brown, Scott Los Angeles, California, USA sbrown@artcenter.edu www.spicybrown.com
* Tutorial: “Designing for Usability” in Chapter 3 Corsaro, Sandro sandro corsaro animation Los Angeles, California, USA info@sandrocorsaro.com www.sandrocorsaro.com
* Tutorial: “Flash Character Design Strategies” in Chapter 13 Lott, Joey Valley Village, California, USA joey@person13.com
* Tutorial: “Adding New Tools to Flash,” in Chapter 4, and sendmail.pl script on the CD-ROM: Cross-Reference in ch29
1113
Part IX
Appendixes
Stumpf, Felix Stuttgart, Germany info@felixstumpf.de www.felixstumpf.de
* Tutorial: “Using Video As a Basis for Fluid, Hand-Drawn Animation” in Chapter 13 Turner, Bill Turnertoons Productions, Inc. Melbourne, Florida, USA * Animation examples and tutorial: “Lip-Syncing Cartoons” in Chapter 13 Winkler, Tom doodie.com Hollywood, California, USA tomwink@earthlink.net www.doodie.com
* Animation examples in Chapter 10
1114
Digital Audio Basics
I
f you plan carefully and pay attention to technical detail, sound can add dimension to your Flash projects. That’s because sound introduces another mode of sensory perception. Coordinated with visual form and motion, sound deepens the impact and can even enhance the ease of use of your Flash creation. For detailed information on adding sound to your Flash productions, refer to Chapter 14, “Adding Sound.” Chapter 14 explains how to work with imported sound in Flash CS4, covering topics from codecs and compression to syncing to behaviors.
CROSS-REF
Understanding the Basics of Sampling and Quality Before you begin integrating sound with your Flash project, it’s important to understand the basics of digital audio. To help you with this, this appendix is dedicated to sampling, bit resolution, and file size.
What is sound? Hearing is one of our five senses; it’s the sense that’s produced when vibrations in the air strike the aural receptors located within your ears. When you hear a sound, the volume of the sound is determined by the intensity of the vibrations, or sound waves.
1115
IN THIS APPENDIX Audio sampling and quality basics Production tips
Part IX
Appendixes
The pitch that you hear — meaning how high (treble) or low (bass) — is determined by the frequency of those vibrations (waves). The frequency of sound is measured in hertz (abbreviated as Hz). Theoretically, most humans have the ability to hear frequencies that range from 20 to 20,000 Hz. The frequency of the sound is a measure of the range of the sound — from the highest high to the lowest low. It’s important to note here that, when starting to work with sound, the most common error is confusing the frequency of the sound with the recording sample.
What affects the quality and size of sound files? When you add sound to a Flash movie, a number of factors affect the final quality of the sound and the size of the sound file. The quality of the sound is important because it determines the aesthetic experience of the sound. The file size is important because it determines how quickly (or slowly) the sound arrives at the end user’s computer. The primary factors that determine the quality and size of a sound file are sample rate and bit resolution.
Sample rate The sample rate, measured in hertz (Hz), describes the number of times an audio signal is sampled when it is recorded digitally. In the late 1940s, Harry Nyquist and Claude Shannon developed a theorem, which said that, for optimal sound quality, a sampling rate must be twice the value of the highest frequency of a signal. Thus, the higher the sample rate, the better the audio range. Generally, higher sample rates result in a richer, more complete sound. According to Nyquist and Shannon, in order for the audible range of 20 to 20,000 Hz to be sampled correctly, the audio source needs to be sampled at a frequency no lower than 40,000 Hz, or 40 kHz. This explains why CD audio, which closely resembles the source sound, is sampled at 44.1 kHz.
NOTE
A sound sample refers to one “analysis” of a recorded sound, whereas a sound file refers to the entire collection of samples recorded, which compose a digital recording.
The less a sound is sampled, the further the recording will deviate from the original sound. However, this tendency toward loss of the original quality of the sound yields one advantage: When the sample rate of a sound file is decreased, the file size drops proportionately. For example, a 300KB, 44.1 kHz sound file would be 150KB when saved as a 22.05 kHz file. See Table C.1 for more details on how sample rates affect quality. Because the native playback rate of most common audio cards is 44.1 kHz, sound that is destined for playback on any computer should be a multiple of 11.025. Thus, we recommend sample rates of 44.1 kHz, 22.05 kHz, and 11.025 kHz for any use on computers. (Although sample rates that deviate from the rule of 44.1 may sound fine on your development platform, and may sound fine on many other computers, some may have problems. This simple rule goes a long way toward reducing complaints of popping and distorted sound.) These standard rates become more important with Flash. When Flash imports sounds that are not multiples of 11.025, the sound file is
1116
Digital Audio Basics resampled, which causes the sound to play at a lower or higher pitch than the original recording. This same logic applies to sound export, which we discuss in Chapter 14. Finally, although Flash menus list sample rates as 11, 22, and 44, these are abbreviations for the truly precise sample rates of 11.025, 22.05, and 44.1 kHz. TABLE C.1
Audio Sample Rates and Quality Sample Rate
Quality Level
Possible Uses
48 kHz
Studio quality
44.1 kHz
CD quality
Sound or music recorded to a digital medium such as miniDV, DAT, DVCam, and so on High-fidelity sound and music
32 kHz
Near-CD quality
Professional/consumer digital camcorders
22.050 kHz
FM radio quality
Short, high-quality music clips
11.025 kHz
Acceptable for music
Longer music clips; high-quality voice; sound effects
5 kHz
Acceptable for speech
“Flat” speech; simple button sounds
Although the Flash Player can play a wide range of sampling rates with runtime assets, the Flash Player resamples all audio to 44.1 kHz during playback. You may want to make sure that all external assets that you intend to play at runtime use 44.1 kHz for consistency.
NOTE
Bit resolution The second key factor that influences audio quality is bit resolution (or bit depth). Bit resolution describes the number of bits used to record each audio sample. Bit resolution is increased exponentially, meaning that an 8-bit sound sample has a range of 28, or 256, levels, whereas a 16-bit sound sample has a range of 216, or 65,536, levels. Thus, a 16-bit sound is recorded with far more information than an 8-bit sound of equal length. The result of this additional information in a 16-bit sound is that background hiss is minimized, while the sound itself is clearer. The same sound recorded at 8-bits will be noisy and washed out. A 16-bit sound file is twice the size of the same file saved at 8-bit quality. This is due to the increase in the amount of information taken to record the higher-quality file. So, if your sound is too big, what can you do? Well, a sound that’s been recorded at a higher bit resolution can be converted to a lower bit resolution, and a sound with a high sample rate can be converted to a lower sample rate. Although a professional studio might perform such conversions with hardware, you can do either of these conversions with software.
1117
C
Part IX
Appendixes
If you’re having difficulty understanding the significance of bit depths, yet are familiar with the intricacies of scanning photographic images, consider the difference between an 8-bit grayscale image and a 24-bit color image of equivalent dimensions. The file size for the 8-bit grayscale image (such as a black-and-white photograph) is much smaller than the 24-bit color image (such as a color photograph). The grayscale image doesn’t have as much tonal information — only 256 levels of gray — yet the 24-bit color image records a range of 16.7 million colors. Unlike photographs, sound samples don’t require anything close to a range of 16.7 million values. Also, 16-bit sound samples deliver a dynamic range of over 64,000 values, which is more than the human ear can detect.
TIP
Table C.2 lists the various bit depths of sound along with their quality levels and possible uses. TABLE C.2
Audio Bit Resolution and Quality Bit Depth
Quality Level
Possible Uses
16-bit
CD quality
High-fidelity sound and music
12-bit
Near-CD quality
Professional/consumer digital camcorder audio
8-bit
FM radio quality
Short, high-quality music clips
4-bit
Acceptable for music
Longer music clips; high-quality voice; sound effects
As hardware technology improves, we’re seeing even better audio bit resolution beyond the 16-bit and 44 kHz range. The DVD-Audio format, for example, offers audio bit resolutions of 16, 20, or 24, and sampling rates of 48, 96, or 192 kHz. Obviously, these extraordinarily high-fidelity recordings are appreciated by extreme audiophiles who have superior playback devices and speakers. Don’t worry if your multimedia presentations don’t use such extremes — trust us when we say that 16-bit 44 kHz audio is more than enough quality for average computer-audio devices and speakers.
NOTE
See Figures C.1 and C.2 for a comparison of the differences between sounds at different sample rates and bit depths. Both figures show a waveform derived from the same original sound file, differing only in their sample rates and bit depths. The waveform of the 16-bit 44.1 kHz sound has twice as many points — or samples of information — as the 8-bit 11.025 kHz sound. Because the 16-bit 44.1 kHz sound has more samples, the gap between each sample isn’t as large as the gaps of the 8-bit 11.025 kHz sound. More samples result in a much smoother, cleaner sound. A common mistake novices make with sound is the assumption that 8-bit audio is acceptable, especially because it ought to result in a much smaller file than 16-bit sound. This is wrong for at least two reasons. First, 8-bit is unacceptable because it sounds far worse than 16-bit sound. Second, the horrible sound does not pay for itself in diminished file size because most audio compression codecs (especially those used by Flash) won’t work with 8-bit sound.
TIP
1118
Digital Audio Basics
FIGURE C.1 A waveform of a sound sampled at 44.100 kHz with a 16-bit resolution, as displayed in a high-end sound application
Channels Audio files are either mono (single channel) or stereo (dual channel: left and right). Stereo files are twice the size of mono files because they have twice the information. Most audio-editing applications offer the option to mix the two stereo channels together and either save or export a stereo sound to a one-channel mono sound. Most audio applications also have the capability to save the right or left channel of a stereo sound separately as a .wav or .aif file. With the more robust, multitrack-editing applications such as Deck, ProTools, Sound Forge, or Cool Edit Pro, it’s not unusual to work with eight or more audio tracks — limited only by your system configuration. As you may imagine, these applications give the sound artist greater control over the final sound mix. For use in Flash, these multitrack audio project files need to be “bounced” or mixed down to a stereo or mono file in order to be saved as .wav or .aif files.
1119
C
Part IX
Appendixes
FIGURE C.2 The same sound that is shown in Figure C.1, but it’s down-sampled to 11.025 kHz with an 8-bit resolution
Getting Tips on Production The primary goal of sound optimization for limited delivery networks (such as the Internet) is to deliver an acceptable quality without a large file-size “cost.” You should be concerned about the file size of your audio clips for several reasons: n Sound files require a large amount of drive space. n Managing large sound files and importing them into Flash can be cumbersome and slow.
1120
Digital Audio Basics
n Download times for large, elaborate sound clips (even when heavily compressed upon export from Flash) can be detrimental to the appreciation of your Flash project (even if your target audience has what may be considered a high-speed Internet connection). When you’re working with audio clips, it’s important to create the shortest audio clips possible. That means trimming off any excess sound that you don’t need, especially any blank lead-in or lead-out handles (also called in and out points) at either the beginning or the end of a clip.
CROSS-REF
We discuss trimming excess sound briefly in Chapter 14, “Adding Sound,” with reference to Flash’s sound tools.
If you plan to have a background music track in your Flash project, it’s a good idea to use a small audio clip that can be looped.
CROSS-REF
We describe looping audio clips in Chapter 14, “Adding Sound.”
Here is a simple formula to determine the file size, in bytes, of a given audio clip: Seconds of audio × sample rate × # of channels × (bit depth ÷ 8) = file size
NOTE
In the preceding formula, the sample rate is expressed in Hz (hertz), not kHz (kilohertz). The bit depth is divided by 8 because there are 8-bits per byte.
Thus, a 20-second stereo audio loop at 8-bits, 11 kHz would be calculated like this: 20 sec × 11,025 Hz × 2 channels × (8-bits ÷ 8-bits/byte) = 441,000 bytes = 430KB There are two schools of thought regarding the ideal quality of sound files for import into Flash. These schools are pretty much divided into those who have high-end sound-editing tools and those who don’t. In an effort to delineate the best path for each group, we’ve noted the following: n If you don’t have high-end sound tools available, you may be among those who always prefer to start with audio source files of the highest possible quality (16-bit, 44.1 kHz is ideal), and then use the Flash sound settings to obtain optimal compression upon export.
CROSS-REF
See Chapter 14, “Adding Sound,” for detailed information on the sound export settings for Flash movies.
n If you do have high-end sound tools available, you may prefer to compose most of your clients’ music from scratch and may very rarely work with the MP3 format before importing into Flash. You may also disagree with those who advise you to bring sound into Flash at
1121
C
Part IX
Appendixes
the highest quality before optimizing. This workflow difference may be attributable to the plethora of options available to those with high-end sound tools. We know of one sound engineer who converts all of his audio to 16-bit, 22.1 kHz mono files, “with major bass reduction,” before importing into Flash. You should always keep in mind that Flash can retain imported MP3 compression settings only with those MP3 files that will be used for non-Stream sync options. Anytime you set a sound to use Stream sync on a timeline, Flash needs to recompress the file with the Stream export settings found in the Publish Settings dialog box. Finally, all linked sounds, or those set to export from the Library and played back via ActionScript, are treated as non-Stream sounds. If you use linked sounds, you may find it useful to import precompressed MP3 files at your preferred bit rate. Flash does not recompress the MP3 file upon export to an .swf file.
1122
Digital Video Basics
A
s you begin to create more complex Flash presentations that include digital video, you need to know how to achieve the highest-quality image and playback. In this appendix, you learn how to prepare a digital video file for use in a Flash CS4 document. After you have successfully created a digital video file, you can learn how to import and use digital video files within a Flash CS4 document by reading Chapter 16, “Displaying Video.”
CROSS-REF
Before you consider importing digital video footage into Flash CS4 or exporting your video with Adobe Media Encoder CS4, you need to plan how the video will be used within the Flash movie (or Web site). Will you be using several video clips for product demonstrations, interviews, or prerecorded events? Will you be using video for special effects such as a timelapse effect of moving clouds or the sun setting? The more footage you plan to use, the more important it is to make sure that you’re acquiring the footage properly — you wouldn’t want to redo all your footage after you’ve seen the results in the Flash movie! This appendix provides tips for making sure that you have the best possible video quality for your Flash presentations.
1123
IN THIS APPENDIX An overview of videotape formats Video production tips File formats for digital video
Part IX
Appendixes
Garbage In, Garbage Out: Controlling Video Quality You may have heard this phrase before, which means that you can’t get something from nothing. Ever tried making a soup with bad ingredients, thinking it would still taste good? The same principle holds true for video production. Four primary factors influence the quality of your video footage: source format, image quality, sound quality, and subject matter.
Source format The source format is the container in which the video is stored, whether it’s a digital recording encoded on miniDV or DVCAM tape, an analog recording on VHS or Hi8 tape, or a file recorded on your digital camera. Each recording medium has inherent resolution limitations — some formats can store more information than others. The more information the medium stores, the higher the quality of the recording. The following list outlines the resolution capacities of common recording mediums. For the purposes of our discussion, this list is restricted to video formats and excludes film formats, such as 35mm or 16mm motion picture film. The video formats are compared by line resolution, which is the number of horizontal scan lines the format can capture. Line resolution is not the definitive attribute for video quality, but it does measure the capacity of potential visual information captured by the camera or recording device. The most important factor to remember when comparing line resolutions is that video is primarily targeted at television screens that, in North America, display 525 lines of resolution. Practically speaking, standard definition (SD) television sets display a maximum of 483 lines of visible resolution — the remaining lines convey other information such as the sync pulse. High-Definition TV (HDTV) is capable of displaying up to 1,080 lines of resolution, and many multimedia producers are using HD cameras to record video.
NOTE
n VHS, VHS-C, or 8mm videotape: These tape formats, especially VHS, are common video formats in use by consumers today. The average household VCR records video in VHS format. These tape formats can record about 240 lines of resolution. This resolution is less than half of the potential scan lines that can be shown on a TV screen, which is why the VHS recordings of your favorite TV shows don’t exactly match the live broadcasts. These tape formats are analog in nature — the signal they record is not digital and can deteriorate from copy to copy. To translate this tape format into digital video for use in a multimedia production, you need to capture the footage with an analog video capture card.
1124
Digital Video Basics
n S-VHS or Hi8 videotape: S-VHS and Hi8 video use the same tape sizes as their VHS and 8mm equivalents, but they capture up to 400 lines of resolution. This resolution capacity comes very close to the 525 lines of resolution that a television can display. You probably won’t encounter many S-VHS camcorders anymore, but Hi8 video camcorders are still popular and in use today. Although the video quality is a noticeable improvement, the video signal is still analog, so as with VHS, you must capture it with an analog video capture card. n miniDV, Digital8, or DVCAM tape: A popular breed of video recording devices for consumer, prosumer, and professional use is the DV (Digital Video) format. DV formats use the DV codec to digitally record video, while storing audio at near-CD or CD-quality sampling rates. The native resolution for the DV format is 525 lines, but the actual resolution a DV camcorder records varies from model to model. Most high-end DV camcorders are considered broadcast quality, meaning the video image is good enough to use on a television show such as the evening news. Many computer systems today ship with an IEEE 1394 (also known as FireWire or iLink) port to capture digital video from DV recording devices. When video is transferred digitally from a camera to a computer over an IEEE 1394 connection, there is no loss of quality. n HDV tape: One of the newer video recording formats is HDV, or High-Definition Video. HDV content is recorded on the same tape cassette used by miniDV cameras. HDV content uses the same bit rates as miniDV content, but uses MPEG-2 compression to store a much larger frame size — usually 1920 x 1080. Most HDV camcorders record content at 1440 x 1080, but on playback, the content is stretched to 1920 x 1080 with the proper 16:9 aspect ratio. Host HDV camcorders can also record or down-convert HD content to regular standard definition (SD) video, on the fly. Video is transferred from an HDV camcorder or player to a computer by using an IEEE 1394 (also known as FireWire or iLink) cable. Newer HDV camcorders can record directly to an internal hard drive on the camera, enabling videographers to more easily transfer recorded content over USB or FireWire. n Betacam SP, Digital Betacam: These tape formats are for serious video professionals who work in the television industry. Betacam SP has been the industry standard for network television for more than 30 years. Although Betacam SP is an analog format, Digital Betacam (also known as DigiBeta) records video with a proprietary Sony codec. Both formats capture 550 or more lines of resolution. n MPEG file recording: Many digital cameras and camcorders can record MPEG video at various sizes and resolutions. Most digital still cameras use an MPEG codec. Many MPEG recording devices can only capture at line resolutions equal to or less than VHS quality. The popular AVC/H.264 codec, part of the MPEG-4 family of codecs, is becoming more widely used in consumer and professional camcorders. This codec can be used to record incredibly high-quality video with much less bit rate than other codecs, and is commonly used with HD frame sizes such as 1280 x 720 or 1920 x 1080.
1125
D
Part IX
Appendixes
As a general guideline, we recommend using the highest-quality camcorder available with your resources to record video that you intend to use for multimedia presentations within a Flash movie. Several factors beyond the recording format affect the quality of any recording. In the next two sections, we discuss variables that influence the visual and audio portions of a recording.
WEB RESOURCE
If you’re a beginner videographer and want to know more about video resolution, check out the following links:
www.bealecorner.com/trv900/respat hometown.aol.com/ajaynejr/vidres.htm
Image quality Regardless of the source format that you use for your video recording, the recording device may have other limitations. The recorded resolution of your camera may be significantly lower than the upper limit of your recording format’s line resolution. For example, the DV format is capable of storing 525 lines of resolution. However, your specific DV camcorder may have an effective resolution of 490 lines. The following variables can affect the quality of the picture recorded by the camera. Note that this list is by no means exhaustive for the professional videographer — we chose these topics as a general summary to guide you in your video production. n Optics: The characteristics of the lens (or lens system) that your camera uses are known as the optics. The optical quality of video camcorders varies wildly. Many camcorders boast Carl Zeiss lenses, which are known for their precision and accuracy. Some lenses are constructed of plastic, whereas others are glass. Neither lens type is necessarily better than the other, but the only way to accurately judge the optical system of your camera is to conduct extensive testing with a resolution target. n CCD or CMOS: The CCD, or charged-coupled device, is the electronic plate that captures the image that the camera’s lens renders. Newer video cameras are offering a CMOS () chip rather than a CCD, for longer battery life and better color sampling. You can think of the CCD or CMOS as the digital film that’s being exposed to the light coming through the lens. Imaging chips come in a variety of sizes, ranging from 1/4 inch to 1 inch. Although these sizes may sound incredibly small, even 1/4-inch chips can capture amazing detail. The larger a chip is, however, the more information it can capture. Most cameras only have one chip, but some cameras have three chips — one for each color of the RGB (red, green, and blue) spectrum. These are known as three-chip cameras, and they have better color fidelity than single-chip cameras. Color fidelity, simply put, is the measure of how closely the recorded color of an image matches the original colors of the subject. n Tape quality: The quality of the tape on which you record the video can also affect the quality of the overall image. Each tape brand has unique characteristics, such as the type of metal particles that are magnetized onto the tape. Some brands (or stocks) are more durable and can withstand the rigors of repeated recordings. In general, you should always record on a fresh tape — and preferably one listed as premium or high quality.
1126
Digital Video Basics
Make sure that you use the same brand and model of tape consistently throughout a shoot. There are slight color variations and differences in quality in each brand and tape type. Preferably, all the tapes used for a shoot should be manufactured from the same batch, and as such, you should buy bulk boxes of your preferred tape brands and formats.
TIP
n Shutter mechanism: The shutter mechanism is the device that controls how quickly the imaging chip samples the image rendered by the lens. Most camcorders have shutters that record interlaced video, which records two interwoven fields (or separate halves of a picture) to create one frame of video. Have you ever noticed how the image on your TV flickers when you pause a VHS recording? You’re seeing the two fields of the frame alternating. Computer monitors do not display interlaced video. Rather, they use progressive scanning to minimize a flicker effect. Some higher-end camcorders have progressive scan shutters that record the image with higher apparent resolution. We discuss de-interlacing video later in this appendix. n Exposure: You should make every effort to shoot your video footage with the correct exposure. Exposure refers to the amount of light captured by the imaging chip and the shutter mechanism. Some camcorders do not allow you to control the exposure — it’s all automatic. The biggest pitfall for most videographers is underexposing video footage or shooting in low light. When you try to record a poorly lit subject, you tend to get noise in the darkest areas of the image. Video noise is a random pattern of dots that shows up on the image. Finally, make every effort to properly white-balance your shot to suit the color temperature of the dominant light source — some camcorders enable you to control the color temperature. You’ll notice the effects of color temperature in the video samples on the CD-ROM. You learn more about white balance later in this appendix. So what do all these variables boil down to? In a nutshell, we recommend that whenever possible, you should shoot video with a camcorder that has a superior optical system with three imaging chips, use high-quality tapes, and properly control your exposure. Avoid shooting in low light, unless you are shooting with a particular effect in mind, such as infrared lighting.
Sound quality Every videographer should consider how audio is recorded during production. Most video camcorders have a decent built-in stereo microphone, but professional videographers equip themselves with accessories beyond those that ship with the camera. Review the following guidelines for capturing sound with your video recording: n External microphones: To achieve the best audio recording, put an external microphone as close as possible to the source of the sound. If you want to record a person talking, an external microphone, such as a wireless Lavaliere mic that’s pinned to the person’s shirt, collar, or tie, produces a much cleaner recording than the microphone on the camera. n Balanced vs. unbalanced audio: Most microphones you find at electronics stores use a stereo or mono 3.5mm mini-adapter that plugs into the microphone jack on your camcorder. These microphones are considered “unbalanced” audio sources, due to the nature
1127
D
Part IX
Appendixes
of their internal wiring. For many video shoots, this may not pose a problem. However, professional audio engineers use balanced audio for all sound sources. The cabling for balanced audio tends to be a heavier gauge than that of the consumer variety. Many balanced microphones have a three-pin XLR connector, and most camcorders require an XLR adapter to connect these sources to the mini microphone jack. Many professional video cameras have built-in XLR jacks. n Sampling rate and bit depth: Unless you’re using a DV format camcorder, you likely have little or no control over the specific sampling rate and bit depth used to record audio on the camera. DV camcorders enable you to record with either 32 kHz or 48 kHz. 32 kHz audio is recorded at 12-bit, which is suitable for recording dialog and live action. 48 kHz is recorded at 16-bit, which is suitable for recording live musical performances or any other scene requiring high fidelity. n Audio levels: One of the most overlooked aspects of video production is monitoring the audio levels of your source while recording. Most camcorders record audio only with AGC, or Automatic Gain Control. This “feature” allows the camcorder to determine how much an audio signal should be boosted or minimized during recording. Professional audio engineers prefer to manually monitor and adjust sound levels while the recording is taking place. Undesirable side effects of using AGC include amplified background noise during silent periods, audio distortion, and sudden jumps or drops in audio levels. Whenever possible, listen to your audio source through headphones connected to the camera. n Unwanted noise: Do your best to minimize any background noise when you are recording. The microphone(s) connected to your camera pick up more noise than you may realize. Each microphone has a different “pick-up” pattern, determining the range and direction of sound that it receives. In summary, you should record audio as close as possible to the source, using balanced microphones and monitoring the audio feed with headphones connected to the camera. For most video recording, either the 32 kHz or 48 kHz sampling rates yield superior audio reproduction.
Subject matter Last, but by no means least, the type of subject matter you are shooting can influence the results of video compression in video deployed to the Flash platform. When it comes to video compression, the most important factor to remember is variability from frame to frame. That is, how much and how often does your subject matter change? Are you recording the Indy 500, panning race cars accelerating at incredibly fast speeds? Or, are you recording a time lapse of a flower slowly blooming? In general, you will achieve the best results with video compression if the subject matter does not move randomly or quickly.
1128
Digital Video Basics
Here are some general guidelines when choosing and shooting your subject matter: n Use a tripod: One of the most common mistakes amateur videographers make is to handhold the video camcorder. Unless you need to freely move with your camera or intentionally want to introduce shakiness to your video image, always mount your camera on a tripod. n Avoid quick and jerky movements: If you need to follow your subject matter by panning the head on the tripod, practice the movement a few times before recording. Try to be as slow and fluid as possible. The more quickly you pan a video camera while recording, the more likely you’ll see compression artifacts show up in your final video in the Flash movie. n Avoid zooming: Although it may be tempting, do not zoom the lens while recording your subject matter. It’s better to use the zoom to frame the shot before you record. Of course, you may intentionally want to use wild zooming effects to re-create the next Blair Witch mockumentary, but be aware that any rapid movement from zooming the lens will likely compress very poorly in the Flash movie. n Lock focus: All camcorders can auto-focus the lens. If you plan to record a stationary object, you may want to switch to manual focus. If your subject matter moves away from the camera’s focus “spot,” the camera may refocus on areas behind the subject matter. This type of focus drifting may yield very unpleasant compression artifacts in the Flash video. n Watch white balance: White balance refers to how the camera interprets color. You might notice that your skin looks much less appealing under fluorescent light than it does under an incandescent or soft white indoor light bulb. The human eye can “correct” the perception of a light source’s color (or color temperature) with greater ease than an automatic setting on your camera. Be sure to match the white-balance setting on your camcorder to the predominant light source in your video composition. Most cameras have at least two white-balance settings: indoor (for tungsten light) and outdoor (for daylight). Some cameras enable you to perform a custom white balance. To set a custom white balance, focus the entire viewing area on a solid field of white and engage the white-balance lock on your camera. Another factor to consider is the area of the video composition that changes from frame to frame. In a previous example, we mention panning a racecar. In that example, the entire picture changes in every frame. Compression works best on video footage with the least amount of movement per pixel in the frame. For example, if you mount your camera on a tripod and keep the camera motionless, you can record the motion of a single subject, such as the flight of a bee between flowers. In such an example, the video compression with the Sorenson Spark codec is much more effective than it would be in the example of the racecar.
1129
D
Part IX
Appendixes
Although we mention these general rules for better-looking video shoots, it is also crucial to develop a look and feel for whatever you are shooting. Establish a set of rules that apply to everything in the shoot. For example, perhaps you want to shoot everything handheld, rack the focus regularly, underexpose the image slightly, dutch the angle on all wide shots, and so on. With today’s cutting-edge video and film effects, it is more important to develop a style and operate to achieve a consistent look than to worry excessively over conventional dos and don’ts.
TIP
Comparing Video Sources
O
n the CD-ROM in the back of this book, you will find three video samples in the resources folder. You can use these examples to test compression settings in Flash CS4, the Flash Video Encoder, or a third-party utility such as Sorenson Squeeze or On2 Flix. Each sample was recorded with a different camera.
n sample_low.mpg: This video file was recorded with a Sony DSC-S70 Cybershot camera. Although this camera is designed to shoot stills, it can also record MPEG-1 video files. This file was recorded in high-quality mode at 320 x 240, 15 frames per second. The microphone on this camera is mono (single-channel).
n sample_mid.avi: This video file was recorded with a Sony DCR-PC100 miniDV camcorder. This camcorder has a stereo built-in microphone and a single CCD. The quality captured by this camera is average for most DV camcorders. Compare the color temperature of this recording to that of sample_low.mpg and sample_high.avi files.
n sample_high.avi: This video file was recorded with a Sony DSR-PD150 mini-DVCAM camcorder. This professional camera has superior exposure and color temperature control. Among other differences with the previous samples, the audio was recorded with a wireless Shure microphone and a UP4 receiver, which uses a three-pin XLR output. The PD150 can accept this XLR output. When you open these files in some video viewers, the .avi files recorded by the DV camcorders might appear stretched horizontally. The DV format uses non-square pixels, whereas most display devices, such as computer monitors, use square pixels. Unless the video display or video player application compensates for non-square pixels, the video image will appear stretched. Flash CS4’s video import process may not automatically compensate for non-square pixel footage, so make sure you resize the video in the Advanced properties, which we discuss in more detail in Chapter 16, “Displaying Video.” We provided these samples so that you may experiment with them in Flash CS4. You will find that cleaner video (such as that shot with the high-end video camcorder) exhibits less video noise in the compressed version within the Flash document.
1130
Digital Video Basics
Editing Footage After you have recorded the video with your camcorder, it’s time to start editing the footage in a digital video editor such as Adobe Premiere or Apple Final Cut Pro. It’s beyond the scope of this book to fully explain the process of editing video footage, but we offer the following pointers to maximize the compression benefits of the video codecs that the Flash Player uses: n Watch transitions and filter effects: Keep the general rule in mind that we mention previously — refrain from global changes to the entire frame. Some effects and transitions, such as cross-fades and slow dissolves, introduce rapid changes to successive frames of video. These changes require more keyframes to retain quality, and these keyframes add significant weight to the file size of the compressed video. Otherwise, if you don’t want the extra weight, you’ll have to accept less quality in the overall image. n Minimize duration: The shorter you make your finished video clip, the smaller the file size of your Flash movie (.swf). Although you can stream video content just like any Flash content, you should keep in mind the data rate of your target audience. When you finish editing your video, make a master version that can serve other purposes beyond your Flash movie presentation. You may even want to output a final version of the edited footage to DV tape. In the next section, we discuss what output format to use for your edited footage. Later, this output format will be compressed and embedded in the Flash document.
Choosing an Import Format After you complete the editing phase for your video footage, you’re ready to output a final version of your video project that you can use with your Flash document. The following checklist should help you determine how to get the most effective use out of the Flash Player’s video codecs, Sorenson Spark, On2 VP6, or AVC/H.264. Just as you don’t want to re-JPEG a JPEG (that is, save a JPEG file again with more JPEG compression), you will find that it’s best to retain as much original quality from the video as possible before you bring it into Flash. n Frame size: Most video sources are captured and edited at full frame NTSC sizes, such as 640 x 480 and 720 x 480. It’s unlikely that you’ll want to expend the bandwidth required to display this full-frame size. A starting frame size should be 320 x 240; work your way up or down from there. If you are targeting Web users with dial-up connection speeds such as 28.8 or 56 Kbps, you may want to consider a frame size of 160 x 120. Remember, when you scale down a bitmap-based element in the Flash authoring environment, you don’t actually throw away any pixels — the full size of the graphic is retained in the final Flash movie file (.swf).
1131
D
Part IX
Appendixes
n Frame rate: When you capture video from your camcorder to your desktop video-editing application, the video has a frame rate of 29.97 fps (NTSC) or 25 fps (PAL). This frame rate, as with regular video frame sizes, requires more bit rate to play with equivalent quality than a lower frame rate. As a general rule, keep your video frame rate as close as possible to (or lower than) the frame rate of your Flash movie, as defined in the Document Properties dialog box (Modify ➪ Document). Most video on the Internet has a frame rate of 15, 24, or 30 fps. As fast broadband Internet connections become more predominant, you’ll find more and more sites featuring Flash Video that uses video clips with 24, 29.97, or 30 fps. If you plan to load .flv files at runtime into Flash movies with Flash Player 7 or later, the video content’s frame rate can differ from the host Flash movie without any conflict. Slower processors, such as Pentium III or older PowerBook G3 computers, however, may have a more difficult time decoding Flash Video that uses high frame rates such as 24, 29.97, or 30 fps.
NOTE
n Video compression: Use a lossless video codec for your final video file that you export from your video editing software. If you’re outputting a QuickTime file, use the Animation codec set to Best (100%) quality. You can also use the Uncompressed option (available in Apple QuickTime Player Pro or any video-editing application such as Adobe Premiere or Apple Final Cut Pro) when you save your final video file. n Audio compression: Follow the same guidelines for video compression. DV-formatted video stores audio uncompressed. n De-interlacing: We mention earlier in this chapter that video recorded by camcorders is interlaced. However, computer monitors (and the graphics appearing on them) are progressively scanned and do not require interlacing. (You may notice how “soft” your DV footage appears in most desktop video-editing applications; this is due to the even and odd “interlaces” being multiplied to accommodate the progressive scanning of computer video.) The general rule of thumb is to use a de-interlace filter (or export option) on any video footage that you intend to use for computer playback. However, if you resize your video to 320 x 240 or smaller and decrease the frame rate from its original rate, you effectively de-interlace the video footage. Usually, you do not see any difference enabling a deinterlace filter on top of these reductions. After you have gone through this checklist for your video footage, export a final video file that you can compress with Adobe Media Encoder. Most video applications (including Apple QuickTime Player Pro) can resave a finished video file with a new frame size, frame rate, video and audio compressions, and other options such as de-interlacing. Adobe Media Encoder can import a variety of video file formats, listed in Table D.1.
1132
Digital Video Basics
TABLE D.1
Video Import Formats for Adobe Media Encoder Format
Platform
Required Drivers
Description
AVI (.avi) Audio Video Interleaved
Windows Mac
DirectX 7 or later, or QuickTime 4 or later
Standard Windows video format; usually the format in which video is captured on Windows; can use any combination of video and audio codecs
DV (.dv) Digital Video stream
Windows Mac
QuickTime 4 or later
Format saved from applications such as Adobe Premiere or Apple QuickTime Player Pro; uses the DV codec for video and uncompressed audio
MPEG (.mpg, .mpeg) Motion Picture Experts Group
Windows Mac
DirectX 7 or later, or QuickTime 4 or later
Precompressed video in the MPEG-1, MPEG-2, or MPEG-4 codec; a format used by many digital cameras that save to media formats such as Compact Flash (CF) and Memory Stick
QT (.mov) Apple QuickTime
Windows Mac
QuickTime 4 or later
Standard video format on the Mac; usually the format in which video is captured on the Mac; can use any combination of video and audio codecs
WMV (.wmv, .asf) Windows Media files
Windows
DirectX 7 or later
Precompressed video in a modified MPEG-4 codec developed by Microsoft to use with the Windows Media Player
Of the formats listed in Table D.1, we recommend that you import formats that don’t apply any recompression to the original source format of your video. If you can avoid using compressed video such as Windows Media and MPEG files, you can prevent the video codecs available in the Flash Player from introducing further artifacts into the video. Compression artifacts are areas in the video frame where detail is lost. The process of compressing a file already using compression is known as recompression. If you try to import MPEG files into the Mac version of Adobe Media Encoder, you may not be able to convert the audio track in the final output file. Only Windows’ DirectX driver successfully converts both the video and audio tracks in most MPEG files to a format useable in the final video file. To import an MPEG via QuickTime on the Mac, you may need to use an application such as MPEG Streamclip (www.squared5.com) to convert the MPEG to a QuickTime movie that uses another codec.
CAUTION
1133
D
Symbols and Numerics && (ampersand) as logical comparison operator, 769 { } curly braces, 609 = (equals sign) as assignment operator, 768 as comparison operator (==), 768 as equality operator (===), 768 ! (exclamation mark) as inequality operator (!==), 769 as not operator, 768, 769 > (greater than symbol) as alphabetically after operator, 769 as comparison operator, 768 < (less than symbol) as alphabetically before operator, 769 as comparison operator, 768 - (minus sign) as subtraction operator, 768 ( ) parentheses in code, 607 as grouping operator, 768 + (plus sign) as addition operator, 768 as concatenation operator, 769 “ (quotation marks) as string operator, 768 ; semicolons, 609 / (slash) as division operator, 768 || (vertical bars) as logical comparison operator, 769 8-bit color, 206 8-bit lossless source files, 536 8-bit resolution sound, 1118 8mm videotape, 1124 4-bit sound resolution, 1118 32-bit lossless source files, 535–536 3D Rotation tool described, 286 symbols transformed with, 288–292
3D space overview, 286–287 perspective in, 287–288 vanishing point in, 287–288 3D Translation tool described, 286 symbols moved with, 292 3D_rotationFlip.fla file, 370 3D_rotationReverse.fla file, 369 12-bit sound resolution, 1118 24-bit color, 206 24-bit lossless source files, 535–536
A
anchor tag, 949–950 absolute color control, 403–404 absolute path, 632, 634 acceleration in animation, 325 Accessibility panel, 666–669 accessibility support, 665–669 accessing items in shared libraries linking to assets from other movies, 925–926 location for shared library, specifying, 924 overview, 921–922 publishing shared library movie file, 925 setting up a shared library file, 922–924 updating shared assets, 926–928 action/reaction force pairs in animation, 326–327 actions. See also specific actions deleting, 606 deprecated, 608 described, 601 event handlers for, 601–602 gotoAndPlay(), 609–610 gotoAndStop(), 609–610 incompatible, 608 keyframe, adding action to, 619 list of common, 615 navigateToURL(), 613–615
1135
A
Index
actions (continued) nextFrame(), 611 nextScene(), 611–612 play(), 612 prevFrame(), 611 prevScene(), 611–612 stop(), 612–613 used to define variables, 766 actions list adding loop to, 776–777 organization of, 758 Actions panel actions list organization in, 758 Actions toolbox, 605 ActionScript commands in, 757–758 adding actions to Script pane, 605 Check Syntax button, 606 components in, 1015 deleting actions, 606 hidden characters, showing, 757 opening, 603 overview, 603–604 Script Assist area, 605 Script navigator, 605 Script pane, 605 syntax, checking, 758 Actions toolbox (Actions panel), 605 ActionScript accessing commands, 757–758 built-in functions, 777 code syntax { } curly braces, 609 ( ) parentheses, 607 ; semicolons, 609 white space, 607 components in, 1015 data types Boolean, 824 casting, 823 class type, checking, 826–828 function, 824–825 number, 823 object, 785, 824 overview, 821 strict typing in ActionScript 3.0, 826 string, 822 typeof operator used to check, 825 undefined, 825
1136
dot syntax, 633 ECMAScript Edition 4 compliance, 754 expressions conditional, 767–778 creating, 767–778 frame specified by, 610 numeric, 763 overview, 763–764 string, 763–764 Help panel for, 758–759 HTML tags inserted into text fields, 952–954 import keyword, 760 include directive, 760 overview, 603 properties, 777 subroutines, 777–778 symbol instances controlled with, 381–382 variables array access operators, 764 case sensitivity of, 762 creating, 765–766 declaring, 766–767 expressions, 763–764 interactive form created with, 778–782 login sequence created with, 778–782 overview, 761–762 string literals for values, 762–763 versions of, 759–761 ActionScript 3.0 Bible (Wiley publication), 176, 329, 603, 628 ActionScript cue points, 582 ActionScript files (.as), 10 activating layers, 88 panels, 68 active property (Thumbnail class), 1078 ActiveX control, Flash Player as, 718 Adaptive Differential Pulse-Code Modulation (ADPCM) compression settings, 498 overview, 476, 478 Add blend mode, 407 addContextMenu function (Gallery class), 1100 Adjust Color filter Brightness value, 399 Contrast value, 399 Hue value, 400
Index
overview, 397–398 Saturation value, 400 Adobe AIR, 5 Adobe Device Central, 4 Adobe Director, 24 Adobe document import, 4 Adobe Flash Media Encoder, 4 Adobe Help Resource Center, 61 Adobe Illustrator files, 515 Adobe Integrated Runtime (AIR), 15 Adobe Media Encoder CS4 Advanced settings, 565 advantages of, 560 Basic Audio settings, 565–566 Basic Video settings, 563–564 Bitrate settings, 564, 566 Crop tool, 566 Cue points section, 566 general export settings, 562 opening, 559 overview, 559–562, 916 presets in, 561–562 Adobe server technologies, 28 Adobe Soundbooth, 5 ADPCM (Adaptive Differential Pulse-Code Modulation) compression settings, 498 overview, 476, 478 Advanced effect settings (Properties panel), 401–404 agile model, 32 AIFF (Audio Interchange File Format), 474 AIGA Professional Practices in Graphic Design: American Institute of Graphic Arts (Allsworth Press), 38 AIR (Adobe Integrated Runtime), 15 AJAX (Asynchronous Javascript and XML), 24 align attribute embed tag, 716 object tag, 709 Align panel, 146–147 alignment design panels, 146–150 overview, 141 snapping settings, 141–146 allowFullScreen attribute embed tag, 717 object tag, 710
allowMultipleSelection parameter (List component), 1021 allowScriptAccess attribute embed tag, 716 object tag, 710 Alpha blend mode, 407, 408–409 alpha channels (video) keying, steps for, 594 live action footage, 594–597 overview, 594 alpha property (MovieClip objects), 789 alpha (transparency) bitmap graphics, 528–529 fills, adjusting for, 221–222 instances, 181 settings with gradients, 225–227 sliders for, 810–818 strokes, adjusting for, 221–222 ambient sound in character animation, 431 && (ampersand) as logical comparison operator, 769 anchor points, displaying, 139 Angle setting for filters, 388 animation acceleration in, 325 action/reaction force pairs in, 326–327 Alpha blend mode for, 410–411 anticipation in, 321–323 character ambient sound in, 431 anticipation used in, 432 backgrounds and scenery, 454–459 backups for, 428 color in, 441–442 emotion, expressing, 431–432 errors in, finding, 467 file sizes, working with large, 428–431 final output for, 467 gaps in, 442 inbetweening, 437 inverse kinematics (IK), 459–466 keys, 437 lip-syncing, 448–454 model sheet used in, 441 motion, blurring to simulate, 433 motion, expressing, 431–432 music, syncing with, 450
1137
A
A
Index
animation, character (continued) overlapping actions in, 432–433 overview, 428–433 post production for, 468–469 scenes, storyboarding, 428–429 shots, storyboarding, 429 sound effects in, 430–431 sound effects, syncing with, 450 speed coloring in, 442 storyboard for, 428–429 temporary backgrounds in, 442 tweening, 446–448 voices in, 429–431 walk cycles, 437–441 weight of objects in, 432 depth in, 319 enhancements to, 4 environment considerations, 313–314 extending, 356 of filters with motion tweens, 394–395 frame-by-frame adding keyframes, 332–333 creating, 333 described, 329 frame rate and animation timing, 335 multiple frames, editing, 336–338 onion skinning, 335–336 overview, 330–331 slowing pacing by adding frames, 333–334 framing in, 319 of Graphic symbols in Movie Clip, 187–188 guidelines for, 312 inertia in, 324–325 keyframe-based tweened, 329–330 laws of nature used in, 324–327 materials for, 314 motion in, 314–316 multiple animation sequences Main Timeline, organizing symbol instances on, 376–379 overview, 373 symbol instances, reusing and modifying, 379–383 symbol timelines, moving tweens onto, 374–376 Newton’s Laws used in, 324–327 object-based motion tweening, 330 perception, manipulating, 318–323
1138
personality added to, 316–317 secondary motion in, 323 terminal velocity in, 325 tweened classic tweens, 339 motion tweening, 348–362 overview, 338–339 shape tweening, 339–347 types of, 329–330 variables defined for, 312–316 viewpoints in, 319–321 visual tricks commonly used in, 318 animation sequencer component of Flash CS4, 14 anti-aliasing text authortime TextField instances, 964–966 comparing effects, 970 overview, 233 runtime TextField instances, 967–970 antiAliasType:String property, 963 anticipation in animation, 321–323, 432 application menu commands (Properties panel), 245–246 approving a final concept and budget, 38 array access operators, 764 Array class, 831–832 arrays (ActionScript) dynamic menu, creating a, 832–838 index values, 831–832 overview, 831–832 arrow states (Selection tool), 133–134 assembling parts for sliders, 807–810 assets, assembling, 44 assigning event listeners, 1029–1030 Asynchronous Javascript and XML (AJAX), 24 audience, defining, 39 audio. See sound audio compression in video, 1132 Audio Event option (Publish settings for sound), 495 Audio Interchange File Format (AIFF), 474 audio player component of Flash CS4, 13 audio settings (Library panel), 501–503 Audio Stream option (Publish settings for sound), 495 audio track embedded in video, 569 authortime files, 13 shared libraries, 199
Index
sharing, 168 TextField instances, 964–966 updating font symbols at, 255 AutoCAD DXF files, 515 auto-loading first image in Gallery component project, 1075–1077 AVC/H.264 video codec, 557–559, 911 Avery, Tex (animator), 432 AVI (Audio Video Interleaved) format, 1133
B
bold tag, 948 back and forth, making an object move, 878–880 Back easing type, 877 background color, printing, 101 backgrounds and scenery blurring to simulate depth, 458–459 importing video with an alpha channel for, 456 layered backgrounds, building, 456–457 long pans, 457–458 mask layers, using, 457 multiplane pans, 458 runtime bitmap caching, 455 backups for character animation, 428 balance sliders, creating, 861–864 balanced audio sources, 1128 Bandwidth Profiler described, 675 using, 675–681 bandwidth usage, optimizing sounds for, 504–507 base attribute embed tag, 717 object tag, 714 base color, 405 Basic Audio settings (Adobe Media Encoder CS4), 565–566 basic blends, applying, 408 Basic motion section (Motion Editor panel), 363–364 Basic Video settings (Adobe Media Encoder CS4), 563–564 Bazley, Richard (guest expert) animation examples, 318, 324, 433 information on, 1113 The Journal of Edwin Carp, 319, 320–321, 454 Best MP3 compression, 676 Betacam SP tape, 1125
Bevel filters, 389 BevelFilter class, 1081–1083 bgcolor attribute embed tag, 716 object tag, 713 Bind tool, 465–466 bit depth/resolution raster images, 519 sound, 1117–1119, 1128 bitmap buttons in Properties panel, 533–534 bitmap caching (runtime), 550–551 bitmap fills scaling, 274 selecting, 227–228 skewing, 275–276 bitmap graphics alpha effects, applying, 528–529 breaking apart, 297–298 color effects, applying, 528–529 compression settings 8-bit lossless source files, 536 lossy compression, source files with, 537 overview, 535 32-bit lossless source files, 535–536 24-bit lossless source files, 535–536 copying, 528 copying and pasting into Flash from other applications, problems with, 514 cross-browser consistency of, 533 editing, 534 filters, applying, 528–529 Fireworks (PNG) files, importing, 526–528 imported media elements, 176 importing, 521 layered, 523–528 multiple images, importing, 522 naming, 530 overview, 12, 517–518 pasting, 528 Photoshop (PSD) files, importing, 523–526 properties, setting, 529–532 quality, maintaining, 519–520 searches, 304 sequences, importing, 522 sizing, 520 smoothing, 530–531 swapping, 534 tracing, 299–300
1139
B
B
Index
bitmap graphics (continued) vector graphics compared, 512–514 conversion to, 538–539 bitmap handler component of Flash CS4, 12 Bitmap text setting, rendering outlines with, 249 BitmapData class, 1083 Bitrate settings (Adobe Media Encoder CS4), 564, 566 blank keyframes, 91, 94 blend color, 405 blend modes Add, 407 Alpha, 407, 408–409 animated Alpha blend, creating, 410–411 basic blends, applying, 408 compound blends, applying, 408–409 Darken, 406 Difference, 407 effects available, 405–407 Erase, 407, 408–409 Hard light, 407 Invert, 407 Layer, 405, 406 Lighten, 407 Multiply, 406 Normal, 406 Overlay, 407 overview, 404–405 Screen, 407 Subtract, 407 blue frames, 99 blur to simulate depth, 458–459 to simulate motion, 433 sliders for, 816–818 Blur X setting for filters, 388 Blur Y setting for filters, 388 BlurFader component (custom) for Digital Video Production example, 663–665 BlurFilter class, 1083 blurOverlay function (Gallery class), 1084 Bone tool, 460–466 Boolean data type, 824 Bounce easing type, 877
carriage return tag, 948 breadcrumbs, 80
1140
break action to exit loops, 776 breaking apart bitmaps, 297–298 groups, 294 text, 294 brightness of instances, 181 Brightness value (Adjust Color filter), 399 Brown, Scott (guest expert) designing for usability tutorial, 39–43 information on, 1113 browsers cross-browser consistency of bitmap graphics, 533 environment not needed for running movies, 22 support for ExternalInterface API, 729 support for plug-in version of Flash Player, 744–745 browsing, creating buttons for, 657–659 Brush tool drawing tablets, additional options for, 116–117 mode menu, 113–115 overview, 112 Paint Behind mode, 114 Paint Fills mode, 114 Paint Inside mode, 114 Paint Normal mode, 114 Paint Selection mode, 114 shaping brush, 116 sizing brush, 115 Brzyski, Jonathan (artist), 978, 979 Bugzilla (online reporting tool), 45 buildHolders function Gallery class, 1066, 1072 built-in functions for ActionScript, 777 Button component emphasized parameter, 1017 enabled parameter, 1017 how it works, 1018 label parameter, 1017 labelPlacement parameter, 1017 onSignUpClick ( ) handler, 1034–1035 overview, 1017 parameters, 1017–1018 selected parameter, 1018 toggle parameter, 1018 visible parameter, 1018
Index
Button symbols assigning a sound to a, 481–483 combining an action with an event handler to make a, 616–617 Down (press) state, adding sound to, 481–482 invisible buttons, 185, 619–625 Over (rollover) state, adding sound to, 482 overview, 175 testing, 190 using Graphic symbols in, 185–187
C
calcThumbW function (Gallery class), 1067 Canyon Cinema, 315 capturing time events with keyframes, 618–619 Cascading Style Sheet (CSS) creating, 955–956 loading into Flash movie, 956–958 case sensitivity of variables, 762 case statements, 771–772 casting data types, 823 CCD (charged-coupled device), 1126 CD-ROM customer care information, 1112 overview, 1109 plug-ins and applications, installing and using, 1111 reviewing example files, 1110 source files and applications, 1111 system requirements, 1110 troubleshooting, 1111–1112 center point, adjusting, 272–273 centering frames, 89 channels, sound, 1119 character animation ambient sound in, 431 anticipation used in, 432 backgrounds and scenery blurring to simulate depth, 458–459 importing video with an alpha channel for, 456 layered backgrounds, building, 456–457 long pans, 457–458 mask layers, using, 457 multiplane pans, 458 runtime bitmap caching, 455 backups for, 428
color in, 441–442 emotion, expressing, 431–432 errors in, finding, 467 file sizes, working with large, 428–431 final output for, 467 gaps in, 442 inbetweening, 437 inverse kinematics (IK) Bind tool, using, 465–466 Bone tool, using, 460–466 overview, 459–460 pose layer, using, 463–464 keys, 437 lip-syncing expression and, 449 overview, 448–449 shape morphing not used for, 449 tricks for, 449–450 tutorial for, 450–454 model sheet used in, 441 motion blurring to simulate, 433 expressing, 431–432 music, syncing with, 450 overlapping actions in, 432–433 overview, 428–433 post production for, 468–469 scenes, storyboarding, 428–429 shots, storyboarding, 429 sound effects overview, 430–431 syncing with, 450 speed coloring in, 442 storyboard for, 428–429 temporary backgrounds in, 442 tweening motion guides, 447–448 overview, 446 panning, 446 symbol swapping, 446–447 voices in, 429–431 walk cycles, 437–441 weight of objects in, 432 character embedding, 244–245 character scenarios, creating, 39 charged-coupled device (CCD), 1126 Check Syntax button (Actions panel), 606
1141
C
C
Index
CheckBox component enabled parameter, 1019 how it works, 1019 label parameter, 1019 labelPlacement parameter, 1019 overview, 1018 parameters, 1018–1019 selected parameter, 1019 visible parameter, 1019 checking class type, 826–828 checkLetter ( ) function (GameModel class), 1000 checkLocalData ( ) function (GameModel class), 986 checkStatus ( ) function (GameModel class), 1003–1006 child nodes, 944–945 clarifying the solution, 755 class, changing styles for component, 1038 class type checking, 826–828 getQualifiedClassName ( ) method used for checking, 828 is operator used for checking, 826–828 classes, intrinsic, 828 classic motion tweens, 91 classic tweens, 339, 348–349 classid attribute (object tag), 709 cleanStage ( ) function (GameView class), 991 Clear command, 152 Clear Frames command, 95 clearing color, 214 clearTweens function (Thumbnail class), 1091 Click Accuracy setting (Pencil tool), 113 CLICK mouse event, 618 closing embed tag, 717 object tag, 714 Tools panel, 72 CMOS video devices, 1126 code syntax for ActionScript { }curly braces, 609 ( ) parentheses, 607 ; semicolons, 609 white space, 607 codebase attribute (object tag), 709
1142
codecs AVC/H.264, 557–559, 911 On2 VP6, 557–559 On2 VP6-S, 911 options for importing video, 557–559 Sorenson Spark, 557–559 sound, 475 ColdFusion downloading trial version, 937 sendmail.cfm script, 937, 943 collisions in MovieClip objects described, 839 dropTarget property used to detect, 840 hitTestObject ( ) method used to detect, 840–841 hitTestPoint ( ) method used to detect, 841 script-based collisions, 839 time-based collisions, 839 user-initiated collisions, 839 color absolute color control, 403–404 base, 405 blend, 405 in character animation, 441–442 clearing, 214 complementary, 400 contrast in colors, 208–209 default colors, loading, 213 dithering, 206 effective use of, 207–211 effects applied to bitmap graphics, 528–529 applied to instances, 181, 190 8-bit, 206 for fills, 123–124 flat, 207 hexadecimal values for, 207 indexed, 206 intermediate, 206 for Mac platform, 206 for MovieClip objects, 845–855 overview, 206 Pantone system, 211 perception of, 208 properties, 401 relative color control, 402–403 replacing, 213
Index
RGB, 206 sampling colors with Eyedropper tool, 266–267 saving, 214 searches, 304 16-bit, 206 sorting by, 214 sources, 210–211 for strokes, 123–124 Swatches panel custom color table, creating and loading, 216–218 custom color them loaded from Kuler panel, 214–215 custom GIF color palette, loading, 215–216 importing custom palettes, 214–218 options for, 213–214 overview, 211–213 24-bit, 206 visual hierarchy, 209–210 Web-safe, 206–207, 214 for Windows platform, 206 Color Effect section (Motion Editor panel), 364 Color Effect settings (Properties panel), 401 Color panel bitmap fills, selecting, 227–228 fill colors, adjusting transparency of, 221–222 gradients alpha settings with, 225–227 controlling gradient fill colors, 223–224 editing, 222–227 overview, 222–223 overview, 218–220 strokes, adjusting transparency of, 221–222 Color Schemer, 210 Color setting filters, 388–389 color table, creating a, 216–218 Color Wheel Pro, 400 ColorTransform class multiplier values, setting, 851–855 offset values, setting, 851–855 overview, 795, 845–846 properties for, 846, 851 Combine Objects command, 301–302 ComboBox component dataProvider parameter, 1020 editable parameter, 1020 enabled parameter, 1020
how it works, 1021 onSectionChange ( ) handler, 1035–1036 overview, 1011–1012, 1019 parameters, 1020–1021 prompt parameter, 1020 restrict parameter, 1020 rowCount parameter, 1020 visible parameter, 1020 comments, 92 Common Libraries, 165–166 Community MX, 871 competition, analyzing the, 40 compiled clip symbol for components, 1011–1012 complementary color, 400 complex vector artwork, interpreting, 547–548 Component Inspector panel, 1015, 1016 components in Actions panel, 1015 in ActionScript, 1015 adding to Stage, 1013 Button how it works, 1018 onSignUpClick ( ) handler, 1034–1035 overview, 1017 parameters, 1017–1018 CheckBox how it works, 1019 overview, 1018 parameters, 1018–1019 class, changing styles for component, 1038 ComboBox how it works, 1021 onSectionChange ( ) handler, 1035–1036 overview, 1019 parameters, 1020–1021 compiled clip symbol for, 1011–1012 in Component Inspector panel, 1015, 1016 in Components panel, 1014 custom downloading, 1047 exchanging, 1047 Live Preview of, 1046 overview, 1045–1046 embedded fonts used with, 1039–1040
1143
C
C
Index
components (continued) event listeners assigning, 1029–1030 example, 1029–1030 overview, 1028–1029 syntax for creating, 1029 Gallery component project auto-loading first image, 1075–1077 component definition, 1102–1105 constructing the Gallery component, 1057–1060 data properties for Gallery class, building, 1061–1063 EasyFilter.as file, 1056 existing component class files, copying, 1102 feature set description, 1050–1051 final deployment, changing script paths for, 1105 full-size JPEG, building a right-click download menu item for, 1099–1101 image captions, 1094–1096 JPEG-Meta.php script, 1055 loading full-size images, 1071–1074 loading transition, 1083–1090 main_starter.fla file, 1056–1057 Phase 1: Setting Up the Gallery Class, 1055–1060 Phase 2: Loading Thumbnails into the ScrollPane, 1060–1071 Phase 3: Displaying the Full-Size JPEG Image, 1071–1077 Phase 4: Enhancing the Thumbnail and Image States, 1077–1101 Phase 5: Finalizing the Component, 1102–1105 resize.php script, 1055 scroll bar, updating, 1075–1077 selected thumbnail, framing, 1081–1083 selected thumbnail, tracking, 1077–1081 server-side scripting requirements, 1051–1055 starter files, reviewing, 1056–1057 thumbnail button handlers, 1096–1099 thumbnail image, loading, 1064–1066 transitioning thumbnail states, 1090–1094 uploading scripts and images to your Web server, 1060–1061 global style formats, 1037
1144
individual instances, changing styles for, 1038–1039 in Library panel, 1015 List how it works, 1022 overview, 1021 parameters, 1021–1022 modifying, 1016, 1036–1039 in movie, 1031–1036 overview, 175, 1010 ProgressBar, 1044–1045 in Properties panel, 1016 RadioButton how it works, 1023–1024 overview, 1022 parameters, 1023 reasons for using, 1010–1011 removing from movies, 1016 ScrollPane how it works, 1025 overview, 1024 parameters, 1024–1025 skins, modifying, 1041–1042 TextArea how it works, 1027 overview, 1025 parameters, 1026 UILoader, 1043–1044 UIScrollBar how it works, 1028 overview, 1027 parameters, 1027–1028 Components panel, 1014 compound blends, applying, 408–409 compound shapes, 302–304 compression with Adobe Media Encoder CS4, 559–566 artifacts, 1133 Best MP3, 676 Fast MP3, 676 Medium MP3, 676 settings for bitmap graphics 8-bit lossless source files, 536 lossy compression, source files with, 537 overview, 535 32-bit lossless source files, 535–536 24-bit lossless source files, 535–536 video, 1132
Index
concept, establishing, 32–38 condenseWhite parameter (TextArea component), 1026 conditional expressions (ActionScript) case statements, 771–772 if statements, 769–771 if/else statements, 769–771 loops for, 774 for . . . in, 774–775 actions list, adding loop to, 776–777 break action to exit, 776 continue action to restart, 776 creating, 776–777 do . . . while, 774 for each, 775 overview, 773 while, 773–774 operators described, 767 general, 767 list of, 768–769 logical, 768 numeric, 767 string, 768 switch() statements, 771–772 Connect Lines setting (Pencil tool), 113 Conner, Bruce (artist), 315 consistency of formatting, 20 container tags (XML), 944 content for each area, creating, 646–652 structuring the, 40 contextual menu layers, 97–98 Movie Explorer, 198–199 overview, 66 continue action to restart loops, 776 continueTo ( ) method (Tween class), 882 contrast in colors, 208–209 Contrast value (Adjust Color filter), 399 contributors, list of, 1113–1114 control added to animation along motion path, 359–360 Controller, 85–86 controlTweens function (Thumbnail class), 1091 conversion to curve point, 139
Convert Lines to Fills command, 278 converting raw shape into Graphic symbol, 183–184 Copy command, 151 Copy Motion command, 362 Copy steps option (History panel), 307 copying bitmap graphics, 514, 528 existing component class files, copying, 1102 frames, 94 scenes, 81 with Text tool, 239 vector graphics, 543 corner points behavior of, 122 conversion to curve point, 139 Corsaro, Sandro (guest expert) animation examples, 319, 322 information on, 1113 tutorial: Flash Character Design Strategies, 442–446 Create Motion Tween command, 352 createAlphabet ( ) function (GameController class), 993–994 createDisplayedWord ( ) function (GameModel class), 998 createNewRound ( ) function (GameModel class), 995–996, 997 createStyles ( ) function (GameView class), 992 Crop tool, 566 cross-browser consistency of bitmap graphics, 533 Crugnola, Alessandro (Flash Switcher), 724 CSS (Cascading Style Sheet) creating, 955–956 loading into Flash movie, 956–958 cue points ActionScript, 582 creating, 582–594 embedded, 581–582 overview, 581–582 Cue points section (Adobe Media Encoder CS4), 566 { } curly braces, 609 currentFrame property for MovieClip objects, 790 curve points, behavior of, 122 curves, optimizing, 549
1145
C
C
Index
customer care information on CD-ROM, 1112 customizing color table, 216–218 color theme loaded from Kuler panel, 214–215 components downloading, 1047 exchanging, 1047 Live Preview of, 1046 overview, 1045–1046 eases, 352, 367 filter setting, 392–394 GIF color palette, 215–216 motion presets, 362 symbol spray pattern created with Spray Brush tool, 154–155 Tools panel, 72–73 UI components, 578–581 workspace layouts, 68–69 Cut command, 151
D
Darken blend mode, 406 data management with states input state, 935 output state, 936 overview, 934 send state, 935–936 wait state, 936 text fields used to store and display data dynamic text fields, 932–934 input text fields, 930–932 user comment form, creation of, 936–943 XML data used in Flash movies, 944–946 data properties (Gallery class), 1061–1063 data types (ActionScript) Boolean, 824 casting, 823 class type checking, 826–828 getQualifiedClassName ( ) method used for checking, 828 is operator used for checking, 826–828 function, 824–825 number, 823 object, 824 overview, 785, 821
1146
strict typing in ActionScript 3.0, 826 string, 822 typeof operator used to check, 825 undefined, 825 database, sending data from movie to, 21 data-driven applications, 29 data-driven presentations, 29 dataProvider parameter ComboBox component, 1020 List component, 1021 Debreuil, Robin (graphic symbols versus movie clip symbols), 177 Debreuil, Sandy (graphic symbols versus movie clip symbols), 177 declaring variables in ActionScript action used to define variables, 766 HTML, establishing variables with, 767 loading variables from predefined source, 766 Deco tool effects made with, 156 Grid Fill effect, 156, 158 overview, 152–153 reflected patterns with, 159–160 Symmetry Brush effect, 156, 159–160 tiling patterns with, 158 Vine Fill effect, 156, 157 default colors, loading, 213 default layout, 62–64 default settings for keyboard shortcuts, 69 defining functions, 829–830 defining the problems, 754–755 de-interlacing video, 1132 deleting actions, 606 components, 1016 filters, 387 layers, 89, 97, 98 MovieClip objects, 818–820 scenes, 81 shape hints, 346 text with Text tool, 238 demo versions, 1111 deploying video files with Flash CS4, 570–575 deprecated actions, 608 depth display on Timeline, 87 depth in animation, 319 Deselect All command, 152 deselecting items, 132
Index
design panels Align panel, 146–147 Info panel, 147–149 overview, 146 Transform panel, 149–150 designing for usability audience, defining, 39 character scenarios, creating, 39 competition, analyzing the, 40 content, structuring the, 40 goals and mission of site, defining, 38–39 “good design,” defining, 40 identifying factors of usability, 40–42 mockups of site, building, 43 testing site on real users, 43 Designing Interactive Digital Media (Iuppa), 38 desktop application authoring program component of Flash CS4, 15 Detect Flash Version feature, 719 detection capabilities, enhancements to, 5 of Flash Player with Flash CS4, 719–724 forcing content without a check, 718–719 overview, 717 sniffers for, 718–719 with SWFObject, 724–728 device fonts overview, 249 Use Device Fonts setting, 249–250 device sound files, 477, 478 devicefont attribute embed tag, 716 object tag, 713 DHTML (Dynamic HTML), 24, 633 Difference blend mode, 407 Digital Betacam tape, 1125 Digital Video Production example accessibility support, 665–669 BlurFader component (custom) for, 663–665 browsing, creating buttons for, 657–659 content for each area, creating, 646–652 folder structure, setting up a local, 643 keyframes, mapping presentation areas to, 644–646 Main Timeline navigation elements added to, 652–659 as site layout, 641–652
menu, creating text buttons for, 652–657 overview of completed presentation, 641–642 planning, 642–643 properties, determining Flash movie, 643–644 text scrolling with TextArea component, 660–663 Digital Video stream (DV) format, 1133 Digital8 tape, 1125 dim function (Thumbnail class), 1091 dimensions differing in movies, handling, 900 direction parameter (UIScrollBar component), 1027 disabling sounds, 498 display list (Movie Explorer), 196 displayCaption function (Gallery class), 1094–1096 displaying anchor points, 139 displayWord ( ) function (GameView class), 986, 998–999 Distance setting filters, 388 Distribute to Layers command, 423–425 distribution plug-in version of Flash Player, 745 projector, 742 stand-alone Flash Player, 742 dithering, 206 do . . . while loops, 774 docking panels, 67 Document Properties panel, 78 Document window Edit bar, 79, 80 Flash templates, working with, 84 menu options, 82–84 moving, 77 overview, 76–77 Pasteboard area, 78–79 resizing, 77 Scene panel, 80–81 Stage area, 78–79 Stage View control, 79–80 tab order, changing, 77 Timeline panel, 79 documenting ideas in meetings, 32 dot notation, 633 dot syntax, 633 Down (press) state, adding sound to, 481–482
1147
D
D
Index
download status of Flash movie, checking on, 888 downloadable images, 1051 downloadImage function (Gallery class), 1100 downloading custom components, 1047 progressive downloads, 21 trial version ColdFusion, 937 draggable Movie Clips drop position, detecting the, 803–806 locking mouse to center, 802 overview, 801–802 rectangular region, constrain dragging area to, 802 sliders for alpha (transparency), 810–818 assembling parts for, 807–810 for blur, 816–818 building, 810–813 creating, 806–818 positions of, checking, 814–818 for scale, 810–818 drag-select, 132 drawing curved line segments with Pen tool, 119, 122 features, enhancements to, 4 geometric shapes, 104–111 objects Combine Objects command with, 301–302 overview, 301–302 tips for working with, 302 optimizing graphics, 129–130 overview, 103–104 settings for, adjusting, 113 straight line segments with Pen tool, 119, 121–122 tablets, additional options for, 116–117 tools Brush tool, 112–117 Eraser tool, 117–118 Pen tool, 119–123 Pencil tool, 111–112, 113 using, 111–118 Drawing Objects, 173 drop position, detecting the, 803–806 Drop Shadow filters, 390–391 Dropper tool, 228–229 dropTarget property, 790, 806–807, 840
1148
Duplicate command, 152 Duration parameter (Tween class), 877 DV (Digital Video stream) format, 1133 DVCAM tape, 1125 Dynamic HTML (DHTML), 24, 633 dynamic menu, creating a, 832–838 dynamic text fields, 232, 235–236, 932–934
E
Ease values, 352 eases, managing, 366–367 Easing function parameter (Tween class), 876, 877–878 EasyFilter.as file (Gallery component project), 1056 ECMA-262 specification, 633 ECMAScript Edition 4, 754 Edit All command, 152 Edit bar (Document window), 79, 80 Edit button (Properties panel), 534 Edit in Place command, 152 Edit mode, 178 Edit Selected command, 152 Edit Symbols command, 152 editable parameter ComboBox component, 1020 TextArea component, 1026 editable text fields, 232, 235–236 editing bitmap graphics, 534 documents in Project panel, 53 frames, 90–96 groups, 284–285, 294 layers, 96–98 manually editing text overview, 260–261 scaling text, 261 sharing text attributes, 261 vector shapes, converting text into, 261–262 motion paths motion tweening, 356–359 tween spans, 357–359 in Movie Explorer, 197–198 multiple frames, 89 in Scene Stage, 180 shapes, 285–286 sound, 491–494
Index
stacking order, 293 symbol type of instances, 182 symbols in Edit mode, 178 from library, 178–179 Main Timeline, returning to, 179 in new window, 178 overview, 284–285 in place, 178 text, 284–285 with Text tool, 238–239 tween curves in Motion Editor panel, 365–366 video footage, 1131 Effect menu (Properties panel), 493 effective use of color, 207–211 8-bit color, 206 8-bit lossless source files, 536 8-bit resolution sound, 1118 8mm videotape, 1124 Elastic easing type, 877 embed tag align attribute, 716 allowFullScreen attribute, 717 allowScriptAccess attribute, 716 base= attribute, 717 bgcolor attribute, 716 closing, 717 devicefont attribute, 716 Flash movie inserted into Web page with, 718 flashvars attribute, 717 height attribute, 716 id attribute, 716 loop attribute, 715 name attribute, 716 object tag compared, 715–717 opening, 715 overview, 715 play attribute, 715 pluginspage attribute, 717 quality attribute, 716 salign attribute, 716 scale attribute, 716 src attribute, 715 swLiveConnect attribute, 716 type= “application/x-shock wave-flash” attribute, 717
width attribute, 716 wmode attribute, 716 embedded cue points, 581–582 embedded fonts used with components, 1039–1040 embedded video content, formatting, 568–569 Embedded Video symbols, 568 embedding video into a movie, 557 emotion, expressing, 431–432 emphasized parameter (Button component), 1017 empty frames, 91 enabled parameter Button component, 1017 CheckBox component, 1019 ComboBox component, 1020 List component, 1022 RadioButton component, 1023 ScrollPane component, 1024 TextArea component, 1026 End value parameter (Tween class), 876 endframe, 91 environment considerations in animation, 313–314 = (equals sign) as assignment operator, 768 as comparison operator (==), 768 as equality operator (===), 768 Erase blend mode, 407, 408–409 Eraser tool, 117–118 errors in character animation, finding, 467 Essentials workspace, 62, 63 evaluation versions, 1111 event handlers for actions, 601–602 button, combining an action with an event handler to make a functioning, 616–617 capturing time events with keyframes, 618–619 described, 602 for mouse events, 617–618 MovieClip objects, 794–795, 796 overview, 615 event listeners assigning, 1029–1030 example, 1029–1030 overview, 1028–1029 syntax for creating, 1029 EventDispatcher class, 987
1149
E
E
Index
events described, 602 sound, stopping, 487–488 syntax for declaring, 987 evolution of Flash CS4, 18–20 of Movie Clips, 627–628 exchanging custom components, 1047 ! (exclamation mark) as inequality operator (!==), 769 as not operator, 768, 769 executing functions, 830–831 existing component class files, copying, 1102 Expand Fill command, 279–280 expanding static text boxes, 234 expanding timeline, 569 export formats for sound ADPCM (Adaptive Differential Pulse-Code Modulation), 476, 478 device sound files, 477, 478 MP3 (MPEG-1 Audio Layer 3), 477, 478 overview, 476–478 Raw (Raw PCM), 477, 478 Speech (Nellymoser), 477, 478 Export Movie command, 680 exposure, video, 1127 expressions (ActionScript) conditional, 767–769 creating, 767–778 frame specified by, 610 numeric, 763 overview, 763–764 string, 763–764 variables, 763–764 expressions (facial) and lip-syncing, 449 extending tween spans, 356 eXtensible Markup Language (XML) child nodes, 944–945 container tags, 944 Flash movie, loading XML document into a, 945–946 nodes, 944 overview, 24, 944–945 eXtensible Stylesheet Language (XSL), 24 external image files, loading, 904–907 External Libraries, 165–166 external microphones, 1127 external runtime assets loaded into movies, 21
1150
external .swf file, 897–899, 900–902 ExternalInterface API adding actions to Flash movies, 730–731 browser support for, 729 described, 27, 729 JavaScript code to enable actions, 731–732 percentLoaded() method, adding, 733–736 extracting sound from a Flash document, 507–509 Eyedropper tool overview, 229 sampling a fill or stroke with, 266–267
F
facial expressions and lip-syncing, 449 fade effects, 493 Fast MP3 compression, 676 file formats for importing artwork, 515–517 importing, support for, 20 sound export formats ADPCM (Adaptive Differential Pulse-Code Modulation), 476, 478 device sound files, 477, 478 MP3 (MPEG-1 Audio Layer 3), 477, 478 overview, 476–478 Raw (Raw PCM), 477, 478 Speech (Nellymoser), 477, 478 sound import formats AIFF (Audio Interchange File Format), 474 MP3 (MPEG-1 Audio Layer 3), 474, 476 overview, 474–475 QuickTime, 475 Sound Designer II, 475 Sun AU, 475 WAV (Windows Wave), 474 video AVI (Audio Video Interleaved) format, 1133 DV (Digital Video stream) format, 1133 embedded video content, formatting, 568–569 import format, choosing, 1131–1133 Import Video wizard used for formatting the embedded video content, 568–569 MPEG (Motion Picture Experts Group) format, 1133 QT (Apple QuickTime) format, 1133
Index
source format, 1124–1126 WMV (Windows Media files) format, 1133 file size calculation for sound files, 1121 small size of Flash files, advantages of, 20 video, 1131 working with large character animation files, 428–431 file types. See also specific file types Flash ActionScript files, 10 Flash Component files, 11 Flash document files, 7–8, 9 Flash movie files, 8, 10 Flash Video files, 11 overview, 7 FileReference API, 1101 files.php script, 1053 filled frames, 91 filled shapes, 416–418 fills adjusting for, 221–222 bitmap, 274 colors for adjusting transparency of, 221–222 controlling, 223–224 overview, 123–124 conversion to, 278 rotating, 273–274 sizing, 279–280 softening edges of, 280–281 switching with Ink Bottle tool, 267–268 with Paint Bucket tool, 268–269 filter buttons in Movie Explorer, 196 filter effects for text, 262–263 filter video effects, 1131 filters adding, 386 Adjust Color, 397–400 Angle setting, 388 animating filters with motion tweens, 394–395 applying, 528–529 Bevel, 389 Blur X setting, 388 Blur Y setting, 388 Color setting, 388–389 custom filter setting, saving, 392–394 Distance setting, 388
Drop Shadow, 390–391 Filter types option, 389 Gradient Glow, 389 Hide object option, 389 Knockout option, 389 Motion Editor used to control filter interpolation, 395–396 overview, 385–386 presets, saving custom, 392–394 Quality setting, 388 removing, 387 settings for, 386–389 Strength setting, 388 filters property for MovieClip objects, 789 Filters section (Motion Editor panel), 364 final deployment, changing script paths for, 1105 final output for character animation, 467 Find and Replace command, 152 Find and Replace panel, 304–305 Find Next command, 152 finish property (Tween class), 882 Fireworks (PNG) files, importing, 526–528 Fireworks styles for gradients, 224 first project. See Digital Video Production example fixed-width static text boxes, 234 Flash 5 Bible (Wiley publication), 177, 888 Flash 8 Bible (Wiley publication), 22 Flash Component files (.swc), 11 Flash CS4 components of, 12–15 enhancements to, 4–5 evolution of, 18–20 file types, 7–11 integration in, 3–11 uses for, 6, 20–22 when not to use, 22–23 Flash CS3 Professional Bible (Wiley publication), 5, 339, 362, 412, 448, 888 Flash Design for Mobile Devices (Wiley publication), 504 Flash document files (.fla) elements in authoring environment, 9 overview, 7–8 saving, 7 Flash Exchange link (Start Page), 61 Flash Lite, 684 Flash movie files (.swf) format overview, 10
1151
F
F
Index
Flash movie files (.swf) (continued) overview, 8 playing, 10 Flash movies external image files, loading, 904–907 importing artwork, 515 loading XML document into a, 945–946 testing Bandwidth Profiler, using, 675–681 overview, 673–674 size report for, 681 with Test Movie command, 674–675 with Test Scene command, 674–675 video files loaded into, 911–916 Flash MX Bible (Wiley publication), 45, 84, 522 Flash Player as ActiveX control, 718 detection of with Flash CS4, 719–724 forcing content without a check, 718–719 overview, 717 sniffers for, 718–719 with SWFObject, 724–728 enhancements to, 5 evolution of, 18–20 on mobile devices, 744 platforms supported by, 22 plug-in version browser support for, 744–745 distribution of, 745 installation of, 745 overview, 718, 743 platform support for, 744 projector creating, 740–742 described, 739–740 distribution of, 742 licensing of, 742 Publish command used to create, 740–741 stand-alone Flash Player used to create, 741––742 settings for accessing, 746 camera, 748–749 local storage, 747 microphone, 747–748 privacy, 746
1152
stand-alone described, 739–740 disadvantages of, 743 distribution of, 742 licensing of, 742 projector created using, 741–742 terminology, 11 utilities for, 749–750 Flash Project files (.flp), 11 Flash Remoting, 28 Flash site architecture for loading movies, 896 Flash Switcher, 724 Flash templates, working with, 84 Flash Video files (.flv), 11 flashvars attribute embed tag, 717 object tag, 713–714 flat color, 207 Flex Builder, 753 floating panels, 67 FLVPlayback component custom UI components, 578–581 overview, 575 parameters, 575–577 focus, locking video, 1129 folders for layers, 89, 92, 98 in Library panel, 171–172 sound, used to organize, 485 structure, setting up a local, 643 tag, 948 tag, 949 tag, 949 tag, 949 font menus, enhancements to, 4 tag, 949 font symbols authortime, updating font symbols at, 255 creating, 253–255 overview, 176, 252–253 in runtime shared libraries, 256–260 fonts Bitmap text setting, rendering outlines with, 249 device overview, 249 Use Device Fonts setting, 249–250 glyphs, 963 overview, 246
Index
searches, 304 smoothing text with anti-alias settings, 246–249 styles for, 948–949 substituting, 251–252 troubleshooting, 250–251 for . . . in loops, 774–775 for each loops, 775 for loops, 774 forcing content without a check, 718–719 format, selecting, 682–683 formatting consistency of, 20 embedded video content, 568–569 forms overview, 937 user comment form, creation of, 936–943 4-bit sound resolution, 1118 fps (frames per second), 89–90 frame actions, 92 frame controls, Timeline, 89 frame rate and animation timing, 335 usability issues, 44 video, 1132 frame size usability issues, 44 video, 1131 frame spans described, 91 empty frames, 91 endframe, 91 filled frames, 91 Frame View options, 98–100 frame-by-frame animation. See also character animation adding keyframes, 332–333 creating, 333 described, 91, 329 frame rate and animation timing, 335 multiple frames, editing, 336–338 onion skinning, 335–336 overview, 330–331 slowing pacing by adding frames, 333–334 frames blue, 99 centering, 89 copying, 94
cutting, 95 editing multiple, 89 gray, 99 green, 99 inserting, 94 labels for, 92, 610 maximum frame rate, 90 maximum possible, 86 methods for specifying, 610 moving, 93 pasting, 94 previewing, 99–100 printing, 101 removing, 94 renumbering, 611 selecting, 92–93 selecting multiple, 93 several frames, viewing, 89 sizing, 99 Timeline display of, 86 tinted, 99 white, 99 frames per second (fps), 89–90 framesLoaded property for MovieClip objects, 790 framing in animation, 319 Free Transform tool, 261, 271, 283–286 FreeHand files, 515 freeware programs, 1111 full-size JPEG, building a right-click download menu item for, 1099–1101 function data type, 824–825 functional specification, 35–37 functions. See also actions; methods; specific functions built-in functions for ActionScript, 777 creating, determining time for, 829 defining, 829–830 executing, 830–831 naming, 830 overview, 828–829 what they do, 828–829
G
Gallery class addContextMenu function, 1100 blurOverlay function, 1084
1153
G
G
Index
Gallery class (continued) buildHolders function, 1066, 1072 calcThumbW function, 1067 creating, 1057–1060 data properties, 1061–1063 displayCaption function, 1094–1096 downloadImage function, 1100 init function, 1066, 1067, 1084, 1094, 1099 items property, 1061 load function, 1067 loadImage function, 1072, 1094 onImgComplete function, 1085 onImgProgress function, 1085 onThumbClick function, 1072 onThumbInit function, 1075 overlayThumb function, 1084 rootURL property, 1061 selectedIndex function, 1072, 1085 selectedIndex property, 1071, 1072 thumbHeight property, 1061 thumbnail holders in, creating, 1066–1071 thumbScript property, 1061 thumbURL property, 1061 updateScroller function, 1075 Gallery component project auto-loading first image, 1075–1077 component definition, 1102–1105 constructing the Gallery component, 1057–1060 data properties for Gallery class, building, 1061–1063 EasyFilter.as file, 1056 existing component class files, copying, 1102 feature set description, 1050–1051 final deployment, changing script paths for, 1105 full-size JPEG, building a right-click download menu item for, 1099–1101 image captions, 1094–1096 JPEG-Meta.php script, 1055 loading full-size images, 1071–1074 loading transition, 1083–1090 main_starter.fla file, 1056–1057 Phase 1: Setting Up the Gallery Class, 1055–1060 Phase 2: Loading Thumbnails into the ScrollPane, 1060–1071
1154
Phase 3: Displaying the Full-Size JPEG Image, 1071–1077 Phase 4: Enhancing the Thumbnail and Image States, 1077–1101 Phase 5: Finalizing the Component, 1102–1105 resize.php script, 1055 scroll bar, updating, 1075–1077 selected thumbnail framing, 1081–1083 tracking, 1077–1081 server-side scripting requirements, 1051–1055 starter files, reviewing, 1056–1057 thumbnail button handlers, 1096–1099 thumbnail image, loading, 1064–1066 transitioning thumbnail states, 1090–1094 uploading scripts and images to your Web server, 1060–1061 game design, 978 game development. See also Hangman game example described, 977 game design, 978 interaction design, 978 programming, 979–981 sound design, 979 visual design, 979 GameController class createAlphabet ( ) function, 993–994 described, 981 instance for Hangman game, 984–985 positionAlphabet ( ) function, 996–997 view property, 986 GameModel class checkLetter ( ) function, 1000 checkLocalData ( ) function, 986 checkStatus ( ) function, 1003–1006 createDisplayedWord ( ) function, 998 createNewRound ( ) function, 995–996, 997 described, 980–981 gameState property, 991 hangmanStates property, 996 instance for Hangman game, 985–986 isLeft ( ) function, 1000 loadWords ( ) function, 985 lookForMatch ( ) function, 1001–1002 moveToNextRound ( ) function, 1006
Index
onWordsLoaded ( ) function, 985 saveName ( ) function, 1007 saveScore ( ) function, 1008 selectedIndex property, 997 wordList property, 985 gameState property (GameModel class), 991 GameView class cleanStage ( ) function, 991 createStyles ( ) function, 992 described, 981 displayWord ( ) function, 986, 998–999 instance for Hangman game, 984–985 matchStateToClip ( ) function, 996 model setter property, 986–987 onClick ( ) function, 991 onFirstRound ( ) function, 992 onGameState ( ) function, 990–991 onHangmanUpdate ( ) function, 996 onLost ( ) function, 1005 Gap size option (Paint Bucket tool), 270 gaps in character animation, 442 GD library, 1052 general export settings (Adobe Media Encoder CS4), 562 general operators, 767 general principles, Movie Clips, 629 geometric shape tools Line tool, 110–111 Oval Primitive tool, 106–107 Oval tool, 104–105 overview, 104 Polystar tool, 109–110 Rectangle Primitive tool, 107–108 Rectangle tool, 107–108 getQualifiedClassName ( ) method, 828 GIF image files, 515 GIF settings, 696–699 global style formats for components, 1037 glyphs, 963 GNU software, 1111 goals establishing, 32–38 for project, determining, 33–34 site, defining, 38–39 “good design,” defining, 40 gotoAndPlay() action, 609–610 gotoAndPlay method for MovieClip objects, 793
gotoAndStop() action, 609–610 gotoAndStop method for MovieClip objects, 793 Gradient Glow filters, 389 Gradient Transform tool bitmap fill, skewing, 275–276 center point, adjusting, 272–273 fill, rotating, 273–274 lighting effects with, 276–277 overview, 227, 271–272 rules for, 272 scale, adjusting, 274–275 gradients alpha settings with, 225–227 Color panel used to edit, 222–227 controlling gradient fill colors, 223–224 fill colors, controlling, 223–224 Fireworks styles for, 224 Illustrator styles for, 224 linear, 222, 274 overflow styles, 275 overview, 222–223 radial, 222, 274 Graphic Artists Guild Handbook of Pricing & Ethical Guidelines (Graphic Artists Guild), 38 Graphic symbols importing video into, 568 Movie Clip symbols compared, 177, 373 overview, 174–175 storing animations in, 373 graphic text, 261–262 graphics adding, 354 pasting, 355 gray frames, 99 > (greater than symbol) as alphabetically after operator, 769 as comparison operator, 768 green frames, 99 grid toggling, 83 units, changing, 83 Grid Fill effect (Deco tool), 156, 158 gridFitType:String property, 963 grouping raw data, 173–174 groupName parameter (RadioButton component), 1023
1155
G
G
Index
groups breaking apart, 294 creating, 293 editing, 284–285, 294 mask layers with, 418–419 guest experts, list of, 1113–1114 GUI (graphical user interface), 42 guide layers creating, 413–415 motion, 412 overview, 92, 97, 412–413 transforming current layer into, 97 guidelines for animation, 312 guides clearing, 83 editing, 83 locking, 83 showing, 83 Snap To Guides, 144–145
H
Hairline line style, 127 Hand tool, 79 Hangman game example alphabet letters, displaying, 996–997 building the project, 981–982 controller, 981 displayed word, creating the letters of the, 998–999 document class overview, 983–987 game design, 978 Hangman.as document class class name, 984 constructor functions, 984 import statements, 984 methods, 984–985 overview, 983 package name, 983 properties, 985–987 property declarations, 984 initializing the game, 983–989 interaction design, 978 interface creation alphabet, creating, 993–994 text fields, creating, 990–993 Main Timeline overview, 983 model, 980–981
1156
placeholder GameView instance, 988 programming, 979–981 random words, choosing, 997 scripting the game, 982 shared font layer, 987 sound design, 979 starting the game, 995–999 status of game, checking, 1003–1006 user input interpreting, 1000–1003 overview, 1000 storing, 1007–1008 view, 981 visual design, 979 Hangman.as document class class name, 984 constructor functions, 984 import statements, 984 methods, 984–985 overview, 983 package name, 983 properties, 985–987 property declarations, 984 hangmanStates property (GameModel class), 996 Hard light blend mode, 407 Hatched line style, 127 HDV video tape, 1125 height attribute embed tag, 716 object tag, 709 height property for MovieClip objects, 789 Video class, 916 height setting for strokes, 125 help menu options, 62 Tween class, 875 Help panel, 758–759 hertz (Hz), 1116 hexadecimal values for color, 207 Hi8 videotape, 1125 hidden characters, showing, 757 hide ( ) method (Mouse class), 842 Hide object option for filters, 389 hiding mask layers, 423 the selection mesh, 131
Index
highlights for selected item, 131 History panel Clear History option, 307 Copy steps option, 307 History View option, 307 overview, 305–306 Replay steps option, 306–307 Save As Command option, 307–308 hitTest method, 792 hitTestObject ( ) method, 840–841 hitTestPoint ( ) method, 841 horizontalLineScrollSize parameter (List component), 1022 horizontalLineScrollSIze parameter (ScrollPane component), 1025 horizontalPageScrollSize parameter (List component), 1022 horizontalScrollPolicy parameter List component, 1022 TextArea component, 1026 HTML. See also specific tags ActionScript used to insert HTML tags into text fields, 952–954 embed tag align attribute, 716 allowFullScreen attribute, 717 allowScriptAccess attribute, 716 base= attribute, 717 bgcolor attribute, 716 closing, 717 devicefont attribute, 716 Flash movie inserted into Web page with, 718 flashvars attribute, 717 height attribute, 716 id attribute, 716 loop attribute, 715 name attribute, 716 object tag compared, 715–717 opening, 715 overview, 715 play attribute, 715 pluginspage attribute, 717 quality attribute, 716 salign attribute, 716 scale attribute, 716 src attribute, 715
swLiveConnect attribute, 716 type= “application/x-shockwaveflash” attribute, 717 width attribute, 716 wmode attribute, 716 establishing variables with, 767 images inserted into text fields, 958–960 object tag align attribute, 709 allowFullScreen attribute, 710 allowScriptAccess attribute, 710 base attribute, 714 bgcolor attribute, 713 classid attribute, 709 closing, 714 codebase attribute, 709 devicefont attribute, 713 embed tag compared, 715–717 Flash movie inserted into HTML document with, 718 flashvars attribute, 713–714 height attribute, 709 id attribute, 709 loop attribute, 710 menu attribute, 711 movie attribute, 710 opening, 709 overview, 708–709 param name= attributes, 710–714 play attribute, 710 quality attribute, 712 salign attribute, 712 scale attribute, 712 width attribute, 709 wmode attribute, 712–713 overview, 947 page production, 44 Properties panel used to format text, 950–952 settings, 688–695 style sheets applied to text fields, 955–958 supported HTML tags anchor tag, 949–950 bold tag, 948
carriage return tag, 948 font and paragraph styles, 948–949 tag, 948
1157
H
H
Index
HTML, supported HTML tags (continued) tag, 949 tag, 949 tag, 949 tag, 949 italic tag, 948 tag, 949 overview, 948 paragraph tag, 948 <span> tag, 949 tag, 949 underline tag, 948 URL and ActionScript linking, 949–950 SWFObject, creating HTML document with, 726–728 TextEvent.LINK event, 961 TextFormat object used for formatting fields, 954–955 using with Flash, 26–27 when to use, 23 htmlText parameter (TextArea component), 1026 Hue value (Adjust Color filter), 400 Hz (hertz), 1116
I
italic tag, 948 id attribute embed tag, 716 object tag, 709 identifying factors of usability, 40–42 if statements, 769–771 if/else statements, 769–771 IK (inverse kinematics) Bind tool, using, 465–466 Bone tool, using, 460–466 enhancements to, 4 overview, 459–460 pose layer, using, 463–464 Illustrator color table, creating a, 216–218 files, importing, 544–546 styles for gradients, 224 imageData property (Thumbnail class), 1086–1087 images captions, 1094–1096 downloadable, 1051
1158
inserted into text fields, 958–960 loaded into TextField object, 958–960 loading files into Flash movies, 904–907 tag, 949 import keyword, 10, 760 Import Video wizard formatting the embedded video content, 568–569 opening, 566 reviewing settings, 570 source clip, choosing a, 567–568 target Flash Player version, choosing a, 567 video content, controlling, 570 imported media elements bitmaps, 176 font symbols, 176 overview, 175 sounds, 176 vector graphics, 176 video assets, 176 importing artwork Adobe Illustrator files, 515 AutoCAD DXF files, 515 Enhanced Metafile files, 515 file formats supported, 515–517 Flash movie files, 515 FreeHand files, 515 GIF image files, 515 JPEG image files, 516 MacPaint image files, 516 overview, 514 Photoshop image files, 516 PICT image files, 516 PNG image files, 516 QuickTime image files, 516 Silicon Graphics image files, 516 TGA image files, 516 TIFF image files, 517 Windows Bitmap files, 515 Windows Metafile files, 517 bitmap graphics alpha effects, applying, 528–529 color effects, applying, 528–529 compression settings, 533, 535–537 copying, 528 cross-browser consistency of, 533 editing, 534
Index
filters, applying, 528–529 Fireworks (PNG) files, importing, 526–528 importing, 521 layered, 523–528 multiple images, importing, 522 naming, 530 overview, 517–518 pasting, 528 Photoshop (PSD) files, importing, 523–526 properties, setting, 529–532 quality, maintaining, 519–520 sequences, importing, 522 sizing, 520 smoothing, 530–531 swapping, 534 custom palettes, 214–218 file formats, support for, 20 sound formats for AIFF (Audio Interchange File Format), 474 MP3 (MPEG-1 Audio Layer 3), 474, 476 overview, 474–475 QuickTime, 475 Sound Designer II, 475 Sun AU, 475 WAV (Windows Wave), 474 vector graphics bitmap caching (runtime), 550–551 complex vector artwork, interpreting, 547–548 copying, 543 curves, optimizing, 549 Illustrator files, importing, 544–546 importing, 541–546 optimizing, 547–551 pasting, 543 rules for, 540 text converted to outlines, 548–549 video for backgrounds and scenery, 456 codec options for, 557–559 compressing video with Adobe Media Encoder CS4, 559–566 formats for, 1131–1133 overview, 557 inbetweening, 437 #include directive, 10, 760 incompatible actions, 608 index values for arrays (ActionScript), 831–832
indexed color, 206 individual instances, changing styles for, 1038–1039 inertia in animation, 324–325 Info panel, 147–149 info.php file, 1052 information architecture, 34 init function (Gallery class), 1066, 1067, 1084, 1094, 1099 init method, 984–985 initializing the game (Hangman game example), 983–989 Ink Bottle tool overview, 229 switching a fill or stroke with, 267–268 Ink mode (Pencil tool), 112 input state, 935 input text fields, 930–932 installation of plug-in version of Flash Player, 745 plug-ins and applications, installing and using, 1111 instances alpha (transparency), 181 brightness of, 181 changing symbol type of, 182 color effects applied to, 181, 190 modifying, 180–183 overview, 163 swapping symbols, 182–183 tint, 181 of video clip, 569 integration enhancements, list of, 4–5 overview, 3–6 of video, 556–557 interaction design, 978 interactive form created with variables, 778–782 interactive presentations, 28 interactive process clarifying the solution, 755 defining the problems, 754–755 translating the solution into interactive language, 756–757 interface enhancements to, 4 fundamentals default layout, 62–64
1159
I
I
Index
interface, fundamentals (continued) Document window, 76–84 Help menu options, 62 on Macintosh, 62–64 printing, 100–101 Properties panel, 64–66 Start Page, 60–62 Timeline window, 84–100 Tools panel, 71–73 on Windows, 62–64 Hangman game example alphabet, creating, 993–994 text fields, creating, 990–993 intermediate color, 206 intrinsic classes, 828 inverse kinematics (IK) Bind tool, using, 465–466 Bone tool, using, 460–466 enhancements to, 4 overview, 459–460 pose layer, using, 463–464 Invert blend mode, 407 invisible buttons creating, 619–625 overview, 185 is operator, 826–828 isLeft ( ) function (GameModel class), 1000 items property (Gallery class), 1061 Iuppa, Nicholas (Designing Interactive Digital Media), 38
J
Jack’s Page (Web site), 327 JavaScript to enable actions, 731–732 movies browser support for, 729 ExternalInterface API, 729–736 overview, 728 overview, 27, 633 Join menu (Properties panel), 108–109 Jordan, Eric (Interface Design tutorial), 45 Jordan, Lawrence (artist), 315 The Journal of Edwin Carp (Bazley, Richard), 319, 320–321, 454
1160
JPEG files importing, 516 metadata, 1051 resizing, 1051 JPEG settings, 699–700 JPEG-Meta.php script, 1055
K
keyboard shortcuts creating, 70 default settings for, 69 overview, 69–71 Timeline, 86 transferring, 71 keyframes adding, 355 adding action to, 619 adding more frames between, 333–334 blank, 91, 94 capturing time events with keyframes, 618–619 clearing, 95 described, 91 editing contents of, 95 empty, 92 inserting, 94 mapping presentation areas to, 644–646 overview, 330–331 property, 91 keying, steps for, 594 keys, 437 Knockout option for filters, 389 Kuler (Adobe Labs), 210
L
label for frame, 610 label parameter Button component, 1017 CheckBox component, 1019 RadioButton component, 1023 labelPlacement parameter Button component, 1017 CheckBox component, 1019 RadioButton component, 1023
Index
labels comments, 92 frames, 92 scenes, 82 Lasso tool Magic Wand option, 138–139, 298–299 overview, 136–137 Polygon mode, 138 laws of nature used in animation, 324–327 Layer blend mode, 405, 406 Layer section (Timeline), 85 layered backgrounds, building, 456–457 layered bitmap graphics, 523–528 layers activating, 88 adding, 89 advanced features, 411–412 contextual menu, 97–98 deleting, 89, 97, 98 folders for, 87, 89, 92, 98 guide creating, 413–415 motion, 412 overview, 92, 412–413 transforming current layer into, 97 hiding, 88, 97 inserting, 97 locking, 88, 97 mask with filled shapes, 416–418 with groups, 418–419 hiding, 423 locking, 423 overview, 92, 415 with symbol instances, 419–420 with text, 420–423 transforming current layer into, 98 motion guide, 97 moving, 97 overview, 96–97 rearranging, 97 showing, 88 showing all, 97 sound folder used to organize, 485 viewing, 484–485
Timeline controls, 88–89 turning off, 413 unlocking, 88 layout custom workspace layouts, creating, 68–69 for panels, 68 for printing, 101 < (less than symbol) as alphabetically before operator, 769 as comparison operator, 768 levels, sound, 1128 libraries adding items to, 166 Common Libraries, 165–166 editing symbols from, 178–179 External Libraries, 165–166 linking assets between project files, 168 moving assets between, 167 multiple libraries, working with, 166–168 overview, 164 resolving conflicts, 172 shared accessing items in, 921–928 authortime, 199–202 linking a symbol from one project library to another, 200–202 overview, 199 runtime, 199 updating symbols in multiple project files, 202 Library panel audio settings, 501–503 components in, 1015 enhancements to, 5 folders in, 171–172 open files, list of, 166 options menu, 169–171 organizing, 171–172 overview, 164 Library settings for sound, 500–503 licensing projector, 742 stand-alone Flash Player, 742 Lighten blend mode, 407 lighting effects, 276–277 line styles, choosing, 124–127 Line tool, 110–111
1161
L
L
Index
line types made by Pen tool, 121 linear gradients, 222, 274 linear presentations, 28 lines fills, conversion to, 278 optimal file size, editing lines for, 140 strokes compared, 124 linking assets between project files, 168 to assets from other movies, 925–926 a symbol from one project library to another, 200–202 TextEvent.LINK event, 961 URL and ActionScript, 949–950 lip-syncing expression and, 449 overview, 448–449 shape morphing not used for, 449 tricks for, 449–450 tutorial for, 450–454 List component allowMultipleSelection parameter, 1021 dataProvider parameter, 1021 enabled parameter, 1022 horizontalLineScrollSize parameter, 1022 horizontalPageScrollSize parameter, 1022 horizontalScrollPolicy parameter, 1022 how it works, 1022 overview, 1021 parameters, 1021–1022 verticalLineScrollSize parameter, 1022 verticalPageScrollSize parameter, 1022 verticalScrollPolicy parameter, 1022 visible parameter, 1022 live action footage, 594–597 Live Preview of custom components, 1046 load function (Gallery class), 1067 Loader class, 895–899 LoaderInfo.bytesLoaded property, 888 LoaderInfo.bytesTotal property, 888 loadImage function (Gallery class), 1072, 1094
1162
loading files Cascading Style Sheet (CSS) into Flash movie, 956–958 external MP3 audio files into Flash movies, 907–911 Flash video file at runtime, 556 images into Flash movies, 904–907 MP3 audio files into Flash movies, 907–911 video files loaded into Flash movie, 911–916 loading movies dimensions differing in movies, handling, 900 external .swf file into MovieClip holder, 900–902 into movies, 897–899 Flash site architecture for, 896 one primary movie in one page, 897 placing, scaling, and rotating during, 900–902 progressive downloads, 888 proxy servers, loading external files through, 903 several pages, breaking up movies across, 897 loading variables from predefined source, 766 loadWords ( ) function (GameModel class), 985 local test environment, staging a, 44 location for shared library, specifying, 924 Lock Fill option (Paint Bucket tool), 270–271 locking guides, 83 layers, 97 mask layers, 423 mouse to center, 802 logical operators, 768 login sequence created with variables, 778–782 long pans, 457–458 lookForMatch ( ) function (GameModel class), 1001–1002 loop attribute embed tag, 715 object tag, 710 looping sound, 494 loops for, 774 for . . . in, 774–775 actions list, adding loop to, 776–777 break action to exit, 776 continue action to restart, 776 creating, 776–777
Index
do . . . while, 774 for each, 775 overview, 773 while, 773–774 lossy compression, source files with, 537 Lott, Joey (guest expert) Adding New Tools to Flash tutorial, 73–76 Flash ActionScript Bible series, 757, 777 information on, 1113
M
Macintosh platform color for, 206 interface fundamentals for Flash, 62–64 motion presets, 362 Macintosh projector, creating, 703 MacPaint image files, 516 Macromedia Authorware, 25 Macromedia Flash MX 2004 Bible (Wiley publication), 324, 456, 680 Macromedia FlashPaper, 26 Magic Wand option (Lasso tool), 138–139, 298–299 Main Timeline Digital Video Production example navigation elements added to, 652–659 as site layout, 641–652 Hangman game example, 983 moving tweens onto symbol timelines from, 374–376 organizing Movie CIips within, 629–631 organizing symbol instances on, 376–379 returning to, 179 scene structure compared, 649 main_starter.fla file (Gallery component project), 1056–1057 maintenance, 45 Mantis (online reporting tool), 45 manually editing text overview, 260–261 scaling text, 261 sharing text attributes, 261 vector shapes, converting text into, 261–262 margins, printing, 100 mask layers backgrounds and scenery, 457 with filled shapes, 416–418
with groups, 418–419 hiding, 423 locking, 423 overview, 92, 415 with symbol instances, 419–420 with text, 420–423 transforming current layer into, 98 mask property for MovieClip objects, 789 matchStateToClip ( ) function (GameView class), 996 materials for animation, 314 maxChars parameter (TextArea component), 1026 maximum frame rate, 90 maximum possible frames, 86 maxScrollH property, 962 maxScrollV property, 962 Medium MP3 compression, 676 Melody For i-mode (MFI), 475 menu creating text buttons for, 652–657 options in Document window, 82–84 menu attribute (object tag), 711 metadata overview, 1051 sizing video with, 916–920 metallic type, creating, 294–297 methods. See also functions; specific methods Hangman.as document class, 984–985 MovieClip objects overview, 791 playback, 793 position, 792 sound class, 855–857 Microsoft Powerpoint, 25 Microsoft Silverlight, 25 MIDI (Musical Instrument Digital Interface) file format, 475 miniDV video tape, 1125 - (minus sign) as subtraction operator, 768 mission of site, defining, 38–39 miter joins, 108–109 Miter setting (Properties panel), 108–109 mobile devices, Flash Player on, 744 mockups of site, building, 43 mode menu (Brush tool), 113–115 model setter property (GameView class), 986–987
1163
M
M
Index
model sheet used in character animation, 441 Model-View-Controller (MVC) design pattern, 980 Modify Transform menu, 283 modifying components, 1016, 1036–1039 instances, 180–183 Movie Clip instance, 190–192 skins, 1041–1042 symbol instances, 379–383 morphemes, 448 motion blurring to simulate, 433 expressing, 431–432 overview, 314–316 references, 315 secondary, 323 Motion Editor panel Basic motion section, 363–364 Color Effect section, 364 custom eases, managing, 367 custom easing with, 352 eases, managing, 366–367 editing tween curves in, 365–366 Filters section, 364 overview, 362–364 property views in, 365 3D properties, animating, 368–372 Transformation section, 364 tricks for using, 364 used to control filter interpolation, 395–396 motion guide layers, 97, 412 motion guides, 447–448 Motion Picture Experts Group (MPEG) format, 1125, 1133 motion presets, 362 Motion Presets panel, 330, 360–362 motion tweening classic tweens compared, 348–349 control added to animation along motion path, 359–360 creating motion tweens, 349–352 Ease values, 352 editing motion paths, 356–359 orienting, 354 overview, 348–349 presets, working with motion, 360–362 properties of, modifying, 352–354 rotating, 353
1164
synchronizing, 354 tween layers graphics, adding, 354 graphics, pasting, 355 keyframes, adding, 355 symbols, adding, 354 tween spans animation, extending, 356 editing motion paths, 357–359 extending, 356 moving, 356 property keyframes, viewing, 356 target object, replacing, 356 Mouse class hide ( ) method, 842 MovieClip objects, 795 pointer, showing and hiding mouse, 842–845 show ( ) method, 842 mouse cursor, creating a graphic following the, 882–885 mouse events CLICK, 618 event handlers for, 617–618 MOUSE_DOWN, 618, 805 MOUSE_MOVE, 843–845 MOUSE_UP, 618, 805–806 ROLL_OUT, 618 ROLL_OVER, 618 Thumbnail class, 1097–1099 mouseX property for MovieClip objects, 788 mouseY property for MovieClip objects, 788 Move Selected Item arrow (Selection tool), 133, 134 movement, avoiding quick and jerky, 1129 moveToNextRound ( ) function (GameModel class), 1006 movie attribute (object tag), 710 Movie Clips evolution of, 627–628 general principles, 629 Graphic symbols compared, 177, 373 importing video into, 568 interaction with Flash movies, 628–629 Main Timeline, organizing Movie CIips within, 629–631 in multiple timelines, 629–631 overview, 175 paths, 632, 634–635
Index
storing animations in, 373 targeting in Flash CS4, 635–639 Movie Explorer contextual menu, 198–199 display list, 196 editing in, 197–198 filter buttons in, 196 options menu, 197–198 overview, 195 MovieClip objects collisions in described, 839 dropTarget property used to detect, 840 hitTestObject ( ) method used to detect, 840–841 hitTestPoint ( ) method used to detect, 841 script-based collisions, 839 time-based collisions, 839 user-initiated collisions, 839 color for, 845–855 ColorTransform class, 795 draggable Movie Clips drop position, detecting the, 803–806 locking mouse to center, 802 overview, 801–802 rectangular region, constrain dragging area to, 802 sliders, creating, 806–818 event handlers, 794–795, 796 methods overview, 791 playback, 793 position, 792 Mouse class, 795 overview, 785–786 pixel-based text scrolling within, 971–976 positioning, 797–798 PrintJob API, 795 properties appearance properties, 789 internal path, 790 list of, 788–790 overview, 786–787 position properties, 788 size properties, 788–789 timeline, 790 working with, 797–800
removing, 818–820 rotating, 800 scaling, 798–800 with ( ) action, 795 MovieClip.framesLoaded property, 888 MovieClip.totalFrames property, 888 movies. See also Flash movies browser environment not needed for running, 22 components in, 1031–1036 database, sending data from movie to, 21 external runtime assets loaded into, 21 JavaScript and DHTML with browser support for, 729 ExternalInterface API, 729–736 overview, 728 preloading with components, 895–903 with internal assets, 889–895 remote data source, displaying files from, 21 moving assets between libraries, 167 Document window, 77 multiple elements, 132–133 Timeline, 85 tween spans, 356 tweens onto symbol timelines from Main Timeline, 374–376 Mozilla Firefox, 722–723 MP3 (MPEG-1 Audio Layer 3) format compression settings, 498, 499 loading files into Flash movie, 907–911 overview, 474, 476, 477, 478 MPEG (Motion Picture Experts Group) format, 1125, 1133 multimedia authoring program component of Flash CS4, 13 multiplane pans, 458 multiple animation sequences Main Timeline, organizing symbol instances on, 376–379 overview, 373 symbol instances, reusing and modifying, 379–383 symbol timelines, moving tweens onto, 374–376 multiple frames, editing, 336–338 multiple images, importing, 522
1165
M
M
Index
multiple instances, 882 multiple libraries, working with, 166–168 multiple timelines, Movie Clips in, 629–631 multiplier values, setting, 851–855 Multiply blend mode, 406 multiuser interactivity, 21 music, syncing character animation with, 450 Musical Instrument Digital Interface (MIDI) file format, 475 Muybridge, Eadweard (photographer), 315
N
name attribute (embed tag), 716 name property for MovieClip objects, 790 naming bitmap graphics, 530 functions, 830 native size, displaying a video at its, 916–921 native symbols button symbols, 175 components, 175 graphic symbols, 174–175 movie clip symbols, 175 overview, 174 Natzke, Erik (artist), 315 navigateToURL() action, 613–615 navigation elements added to Main Timeline, 652–659 nested structures for symbols adding Movie Clip to Button symbol, 188–190 animating Graphic symbols in Movie Clip, 187–188 button, using Graphic symbols in, 185–187 converting raw shape into Graphic symbol, 183–184 modifying Movie Clip instance, 190–192 overview, 183 NetStream object, 914–915 NetStream.onMetaData ( ) handler, 916–920 new window, editing symbols in, 178 Newton’s Laws used in animation, 324–327 nextFrame() action, 611 nextFrame method for MovieClip objects, 793 nextScene() action, 611–612 9-slice scaling, 192–195 nodes, 944
1166
None easing type, 878 Normal blend mode, 406 number data type, 823 numeric expressions, 763 operators, 767 Nyquist, Harry (sound theorem), 1116
O
object data type, 824 object tag align attribute, 709 allowFullScreen attribute, 710 allowScriptAccess attribute, 710 base attribute, 714 bgcolor attribute, 713 classid attribute, 709 closing, 714 codebase attribute, 709 devicefont attribute, 713 embed tag compared, 715–717 Flash movie inserted into HTML document with, 718 flashvars attribute, 713–714 height attribute, 709 id attribute, 709 loop attribute, 710 menu attribute, 711 movie attribute, 710 opening, 709 overview, 708–709 param name= attributes, 710–714 play attribute, 710 quality attribute, 712 salign attribute, 712 scale attribute, 712 width attribute, 709 wmode attribute, 712–713 object-based motion tweens, 91 offset values, setting, 851–855 On2 VP6 codec, 557–559 On2 VP6-S video codec, 911 onClick ( ) function (GameView class), 991 onFirstRound ( ) function (GameView class), 992 onGameState ( ) function (GameView class), 990–991
Index
onHangmanUpdate ( ) function (GameView class), 996 onImgComplete function (Gallery class), 1085 onImgProgress function (Gallery class), 1085 onion skinning, 89, 335–336 online help for Pen tool, 123 onLoadClick function, 906–907 onLost ( ) function (GameView class), 1005 onSectionChange ( ) handler (ComboBox component), 1035–1036 onSignUpClick ( ) handler (Button component), 1034–1035 onThumbClick function (Gallery class), 1072 onThumbInit function (Gallery class), 1075 onThumbOut function (Thumbnail class), 1096 onThumbOver function (Thumbnail class), 1096 onTweenFinish function (Thumbnail class), 1091 onWordsLoaded ( ) function (GameModel class), 985 open files, list of, 166 opening Actions panel, 603 Adobe Media Encoder CS4, 559 documents in Project panel, 53 embed tag, 715 Import Video wizard, 566 object tag, 709 Publish settings, 495 Timeline, 85 Tools panel, 72 operators described, 767 general, 767 list of, 768–769 logical, 768 numeric, 767 string, 768 optics, 1126 optimal file size, editing lines for, 140 Optimize Curves command, 129–130 optimizing graphics, 129–130 sound, 494–495 vector graphics, 547–551
options menu Library panel, 169–171 Movie Explorer, 197–198 Orb, Jack (teacher), 327 organizational flowchart, 35 organizing Library panel, 171–172 orienting, 354 output state, 936 Oval Primitive tool, 106–107 Oval tool, 104–107 Over (rollover) state, adding sound to, 482 overflow styles for gradients, 275 overlapping actions in character animation, 432–433 Overlay blend mode, 407 overlayThumb function (Gallery class), 1084 Override Sound Settings option, 495
P
paragraph tag, 948 packages naming, 983 overview, 828 Paint Behind mode (Brush tool), 114 Paint Bucket tool Gap size option, 270 Lock Fill option, 270–271 overview, 229 switching a fill or stroke with, 268–269 Paint Fills mode (Brush tool), 114 Paint Inside mode (Brush tool), 114 Paint Normal mode (Brush tool), 114 Paint Selection mode (Brush tool), 114 panels. See also specific panels active, making, 68 docking, 67 floating, 67 layout for, saving, 68 stacking, 67 panning, 446 Pantone color system, 211 Pantone Guide to Communicating with Color (North Light Books), 211 Papervision 3D, 23 paragraph, styles for, 948–949 param name= attributes (object tag), 710–714 parent property for MovieClip objects, 790
1167
P
P
Index
( ) parentheses in code, 607 as grouping operator, 768 Paste in Center command, 151 Paste in Place command, 151 Paste Motion command, 362 Paste Special (PC only) command, 152 Pasteboard area (Document window), 78–79 pasting bitmap graphics, 528 vector graphics, 543 paths absolute, 632, 634 described, 632 relative, 634–635 Pen tool corner points, behavior of, 122 curve points, behavior of, 122 drawing curved line segments with, 119, 122 drawing straight line segments with, 119, 121–122 line types made by, 121 online help for, 123 overview, 119 preferences for, 119 Show pen preview setting, 119 Show precise cursors setting, 119 Show solid points setting, 119 states for, 120 submenu, 120 Pencil tool Click Accuracy setting, 113 Connect Lines setting, 113 Ink mode, 112 overview, 111–112 Recognize Lines setting, 113 Recognize Shapes setting, 113 Smooth Curves setting, 113 Smooth mode, 112 Straighten mode, 112 percentLoaded() method, 733–736 perception of color, 208 manipulating, 318–323 permutation, 317 personality added to animation, 316–317 perspective in 3D space, 287–288 phonemes, 448, 453
1168
Photoshop color table, creating a, 216–218 importing artwork from, 516 (PSD) files, 523–526 PHP files.php script, 1053 JPEG-Meta.php script, 1055 resize.php script, 1055 syntax, 1053 PHP5 determining if your server has PHP installed and enabled, 1052 recommended for Gallery component project, 1052 PICT image files, 516 Pietrovito, Rose (designer), 315 pitch, 1116 pixel-based text scrolling with Movie Clips, 971–976 place, editing symbols in, 178 platform support Flash Player, 22 for plug-in version of Flash Player, 744 play() action, 612 play attribute embed tag, 715 object tag, 710 play method for MovieClip objects, 793 plug-in Flash Player as, 718 installing and using, 1111 version of Flash Player browser support for, 744–745 distribution of, 745 installation of, 745 overview, 743 platform support for, 744 pluginspage attribute (embed tag), 717 + (plus sign) as addition operator, 768 as concatenation operator, 769 PNG image files, 516 PNG settings, 701–703 pointer, showing and hiding mouse, 842–845 points, deleting, 140 Polygon mode (Lasso tool), 138 Polystar tool, 109–110 pose layer, using, 463–464
Index
position property (Tween class), 882 positionAlphabet ( ) function (GameController class), 996–997 positioning MovieClip objects, 797–798 sliders, 814–818 post production for character animation, 468–469 preferences Pen tool, 119 Project panel, 50–53 Selection tool, 133 preloading described, 888 Loader class, use of, 895–899 movies with components, 895–903 with internal assets, 889–895 script routine, 893–894 presentations data-driven, 29 interactive, 28 linear, 28 presets in Adobe Media Encoder CS4, 561–562 saving custom, 392–394 working with motion, 360–362 prevFrame() action, 611 prevFrame method for MovieClip objects, 793 preview mode, 82 previewing frames, 99–100 printing, 101 prevScene() action, 611–612 primitive shapes as raw data, 173 printing background color, 101 content from Flash movies, 22 frames, 101 layout for, 101 margins, 100 overview, 100–101 previewing, 101 PrintJob API, 795 PrintJob class capabilities of, 864–865 tutorials online, 871 using, 865–870
private keyword, 984 procedures. See functions process flowchart, 35–36 Processing (open source tool), 327 production, tips on sound, 1120–1122 profiles for Publish Settings for movies, 704–705 programming and database front end component of Flash CS4, 14–15 ProgressBar component, 895, 1044–1045 progressive downloads, 21, 888 Project panel creating the project, 47–50 editing documents in, 53 enhancements to, 5 opening documents in, 53 overview, 46 preferences, changing, 50–53 publishing projects, 54–55 structure for project, establishing, 46–47 using, 46–55 projector creating, 740–742 described, 739–740 distribution of, 742 licensing of, 742 Publish command used to create, 740–741 stand-alone Flash Player used to create, 741––742 prompt parameter (ComboBox component), 1020 properties ActionScript, 777 color, 401 ColorTransform class, 846, 851 declaring, 984 determining Flash movie, 643–644 Hangman.as document class, 985–987 motion tweening, 352–354 MovieClip objects appearance properties, 789 internal path, 790 list of, 788–790 overview, 786–787 position properties, 788 size properties, 788–789 timeline, 790 working with, 797–800 setting, 529–532
1169
P
P
Index
Properties panel Advanced effect settings, 401–404 application menu commands, 245–246 bitmap buttons in, 533–534 character embedding, 244–245 Color Effect settings, 401 components in, 1016 Edit button, 534 editable text options, 242–244 Effect menu, 493 interface fundamentals for Flash, 64–66 Join menu, 108–109 Miter setting, 108–109 static text options anti-aliasing, 241 auto kerning, 241 fonts, choosing, 240 letter spacing, 241 paragraph formatting, 241–242 positioning text, 240 sizing text, 240 styles, choosing, 240 subscript, 241 superscript, 241 Swap button, 534 text attributes set in, 240–246 used to format text, 950–952 property keyframes, viewing, 356 property views in Motion Editor panel, 365 proxy servers, loading external files through, 903 public keyword, 984 Publish command, 703, 740–741 Publish Preview command, 703 Publish settings movies Flash movie file (.swf) settings, 683–688 format, selecting, 682–683 GIF settings, 696–699 HTML settings, 688–695 JPEG settings, 699–700 Macintosh projector, creating, 703 overview, 682 PNG settings, 701–703 profiles for, 704–705 Windows projector, creating, 703 sound ADPCM compression settings, 498 Audio Event option, 495
1170
Audio Stream option, 495 disabling sounds, 498 MP3 compression settings, 498, 499 opening, 495 Override Sound Settings option, 495 overview, 495 Raw (Raw PCM) compression settings, 499 Set options, 496–500 Speech sample rate setting, 499–500 supporting audio and MP3 playback, 500 publishing Flash movies overview, 681 Publish command for, 703 Publish Preview command for, 703 projects, 54–55 shared library movie file, 925
Q QT (Apple QuickTime) video format, 1133 quality bitmap graphics, 519–520 factors affecting sound, 1116–1119 video, 1126–1127 quality assurance testing, 45 quality attribute embed tag, 716 object tag, 712 Quality setting filters, 388 QuickTime, 475 QuickTime image files, 516 “ (quotation marks) as string operator, 768
R
radial gradients, 222, 274 RadioButton component enabled parameter, 1023 groupName parameter, 1023 how it works, 1023–1024 label parameter, 1023 labelPlacement parameter, 1023 overview, 1022 parameters, 1023 selected parameter, 1023 value parameter, 1023 visible parameter, 1023
Index
random spray pattern created with Spray Brush tool, 153–155 raster images bit depth, 519 resolution, 518–519 raw data Drawing Objects, conversion to, 173 grouping, 173–174 overview, 173 primitive shapes as, 173 Raw (Raw PCM) sound, 477, 478, 499 real-time streaming a Flash video file at runtime, 556 Recognize Lines setting (Pencil tool), 113 Recognize Shapes setting (Pencil tool), 113 recompression, 1133 Rectangle Primitive tool, 107–108 Rectangle tool, 107–108 rectangular region, constrain dragging area to, 802 Redo command, 151 references, 315 reflected patterns with Deco tool, 159–160 Regular easing type, 878 Reinhardt, Robert (author) Flash ActionScript Bible series, 757, 777 PrintJob tutorials written by, 871 relative color control, 402–403 relative path, 634–635 remote data source, displaying files from, 21 removing/deleting components, 1016 filters, 387 MovieClip objects, 818–820 shape hints, 346 renaming scenes, 81 renumbering frames, 611 Repeat command, 151 replacing color, 213 Replay steps option (History panel), 306–307 Reshape Corner arrow (Selection tool), 133, 134 Reshape Curve arrow (Selection tool), 133, 134 resize.php script, 1055 resizing Document window, 77 JPEG files, 1051 Timeline, 85 video, 563–564 resolution, 518–519
resolving conflicts with libraries, 172 restrict parameter ComboBox component, 1020 TextArea component, 1026 reusable template interfaces, 21 reviewing content with SWFObject, 725–726 RGB color, 206 RIA (Rich Internet Application), 29 ROLL_OUT mouse event, 618 ROLL_OVER mouse event, 618 root keyword, 635 rootURL property (Gallery class), 1061 rotating motion tweening, 353 MovieClip objects, 800 rotation property for MovieClip objects, 788 rowCount parameter (ComboBox component), 1020 rulers, toggling, 83 rules for Gradient Transform tool, 272 for vector graphics, 540 runtime bitmap caching, 455 file, 13 shared libraries, 199, 256–260 sharing, 168 TextField instances, 967–970
S
salign attribute embed tag, 716 object tag, 712 sample rate, 1116–1117 sample_high.avi video file, 1130 sample_low.mpg video file, 1130 sample_mid.avi video file, 1130 sampling colors with Eyedropper tool, 266–267 sampling rate, 1128 saturation function (Thumbnail class), 1091 Saturation value (Adjust Color filter), 400 Save As Command option (History panel), 307–308 saveName ( ) function (GameModel class), 1007 saveScore ( ) function (GameModel class), 1008
1171
S
S
Index
saving color, 214 scalable artwork, creating, 278 Scalable Vector Graphics (SVG), 25 scale adjusting, 274–275 sliders for, 810–818 scale attribute embed tag, 716 object tag, 712 Scale option for strokes, 127–129 scaleX property for MovieClip objects, 788 scaleY property for MovieClip objects, 788 scaling MovieClip objects, 798–800 text, 261 Scene panel (Document window), 80–81 Scene Stage, 180 scene structure, 649 scenery and backgrounds blurring to simulate depth, 458–459 importing video with an alpha channel for, 456 layered backgrounds, building, 456–457 long pans, 457–458 mask layers, using, 457 multiplane pans, 458 runtime bitmap caching, 455 scenes adding, 81 copying, 81 deleting, 81 editing, 81 labels for, 82 navigating to, 81 ordering, 81 overview, 80 renaming, 81 storyboarding, 428–429 Screen blend mode, 407 Script Assist area (Actions panel), 605 Script navigator (Actions panel), 605 Script pane (Actions panel), 605 script routine, preloadiing, 893–894 script-based collisions, 839 scroll bar, updating, 1075–1077 scroll properties, 961–962 scrollDrag parameter (ScrollPane component), 1025
1172
scrollH property, 962 ScrollPane component enabled parameter, 1024 horizontalLineScrollSIze parameter, 1025 how it works, 1025 overview, 1024 parameters, 1024–1025 scrollDrag parameter, 1025 source parameter, 1025 verticalLineScrollSIze parameter, 1025 visible parameter, 1025 scrollRect property, 971–976 scrollTargetName parameter (UIScrollBar component), 1027–1028 scrollV property, 962 searches bitmap, 304 color, 304 fonts, 304 sound, 304 symbol, 304 text, 304 video, 304 secondary motion, 323 Select All command, 152 selected parameter Button component, 1018 CheckBox component, 1019 RadioButton component, 1023 selected thumbnail framing, 1081–1083 tracking, 1077–1081 selectedIndex function (Gallery class), 1072, 1085 selectedIndex property Gallery class, 1071, 1072 GameModel class, 997 Selection tool arrow states, 133–134 deselecting items, 132 drag-select with marquee, 132 hiding the selection mesh, 131 highlights for selected item, 131 Move Selected Item arrow, 133, 134 moving multiple elements, 132–133
Index
options for, 135 overview, 131–132 preferences, 133 Reshape Corner arrow, 133, 134 Reshape Curve arrow, 133, 134 Smooth option, 135–136 Straighten option, 135–136 selection tools Lasso tool, 136–139 overview, 130–131 Selection tool, 131–136 Subselection tool, 139–140 ; semicolons, 609 send state, 935–936 sendmail.cfm script, 937, 943 sequences, importing, 522 server test environment, staging a, 44–45 server-side scripting requirements, 1051–1055 setting up a shared library file, 922–924 several frames, viewing, 89 several pages, breaking up movies across, 897 Shannon, Claude (sound theorem), 1116 shape hints adding, 344–347 removing, 346 viewing, 347 shape morphing not used for lip-syncing, 449 shape tweening creating a shape tween, 340–344 overview, 339–340 shape hints, adding, 344–347 shape tweens defined, 91 shapes, editing, 285–286 shaping brush, 116 shared font layer, 987 shared libraries accessing items in linking to assets from other movies, 925–926 location for shared library, specifying, 924 overview, 921–922 publishing shared library movie file, 925 setting up a shared library file, 922–924 updating shared assets, 926–928 advantage of using, 922 authortime, 199 linking a symbol from one project library to another, 200–202
overview, 199 runtime, 199 updating symbols in multiple project files, 202 URL for, 924 sharing text attributes, 261 sharpness:Number property, 963 shots, storyboarding, 429 show ( ) method (Mouse class), 842 Show pen preview setting (Pen tool), 119 Show precise cursors setting (Pen tool), 119 Show solid points setting (Pen tool), 119 showText ( ) function, 959–960 shutter video mechanism, 1127 Silicon Graphics image files, 516 Simple Object Access Protocol (SOAP), 27 site layout, Main Timeline as, 641–652 16-bit color, 206 16-bit resolution sound, 1118 size of sound file, factors affecting, 1116–1119 size report for testing Flash movies, 681 sizing bitmap graphics, 520 brushes, 115 fills, 279–280 frames, 99 Tools panel, 72 video with metadata, 916–920 without metadata, 920–921 skins features, 572 modifying, 1041–1042 / (slash) as division operator, 768 sliders building, 810–813 creating, 806–818 draggable Movie Clips for alpha (transparency), 810–818 assembling parts for, 807–810 for blur, 816–818 building, 810–813 creating, 806–818 positions of, checking, 814–818 for scale, 810–818 slowing pacing by adding frames, 333–334 small size of Flash files, advantages of, 20
1173
S
S
Index
SMIL (Synchronized Multimedia Integration Language), 25–26 Smooth Curves setting (Pencil tool), 113 Smooth mode (Pencil tool), 112 Smooth option (Selection tool), 135–136 smoothing bitmap graphics, 530–531 text with anti-alias settings, 246–249 snapping settings overview, 141 Snap Align, 142, 143 Snap To Grid, 142, 144 Snap To Guides, 144–145 Snap To Objects, 142, 143 Snap To Pixels, 145–146 sniffers, 718–719 SOAP (Simple Object Access Protocol), 27 Soften Fill Edges command, 280–281 softening edges of fills, 280–281 Solid line style, 127 solution, producing a, 34–38 Sorenson Spark codec, 557–559 sorting by color, 214 sound balance sliders, creating, 861–864 balanced audio sources, 1128 bandwidth usage, optimizing sounds for, 504–507 bit resolution/bit depth, 1117–1119, 1128 button, assigning a sound to a, 481–483 channels, 1119 codecs, 475 combining methods for controlling, 503 editing, 491–494 8-bit resolution, 1118 event, stopping, 487–488 export formats ADPCM (Adaptive Differential Pulse-Code Modulation), 476, 478 device sound files, 477, 478 MP3 (MPEG-1 Audio Layer 3), 477, 478 overview, 476–478 Raw (Raw PCM), 477, 478 Speech (Nellymoser), 477, 478 external microphones, 1127 extracting sound from a Flash document, 507–509
1174
fade effects, 493 file size calculation, 1121 4-bit resolution, 1118 import formats AIFF (Audio Interchange File Format), 474 MP3 (MPEG-1 Audio Layer 3), 474, 476 overview, 474–475 QuickTime, 475 Sound Designer II, 475 Sun AU, 475 WAV (Windows Wave), 474 importing sound files, 478–480 layers folder used to organize, 485 viewing, 484–485 levels, 1128 Library settings for, 500–503 loading external MP3 audio files into Flash movies, 907–911 looping, 494 optimizing, 494–495 overview, 176, 1115–1116 pitch, 1116 production, tips on, 1120–1122 Publish settings for ADPCM compression settings, 498 Audio Event option, 495 Audio Stream option, 495 disabling sounds, 498 MP3 compression settings, 498, 499 opening, 495 Override Sound Settings option, 495 overview, 495 Raw (Raw PCM) compression settings, 499 Set options, 496–500 Speech sample rate setting, 499–500 supporting audio and MP3 playback, 500 quality, factors affecting, 1116–1119 quality with video, 1127–1128 sample rate, 1116–1117, 1128 searches, 304 16-bit resolution, 1118 size of file, factors affecting, 1116–1119 Start Sync option, 486 Stop Sync option, 486 stopping, 487–491 storing sound files, 480–481
Index
stream overview, 486 stopping, 489–490 synchronizing to animations, 485–486 timeline adding sound to a, 483–484 organizing sounds on a, 484–485 12-bit resolution, 1118 unbalanced audio sources, 1127–1128 unwanted noise, 1128 VBR (Variable Bit Rate) MP3, 503–504 volume sliders, creating, 861–864 sound class advantages of, 858 balance sliders, creating, 861–864 creating sounds, 858–860 creating SoundTransform object, 861 methods, 855–857 overview, 858 volume sliders, creating, 861–864 Sound Designer II, 475 sound effects in character animation overview, 430–431 syncing with, 450 SoundChannel.soundTransform method, 857 SoundChannel.stop method, 857 sound.load ( ) method, 908–910 Sound.load method, 856 Sound.play method, 856 SoundTransform.pan method, 857 SoundTransform.volume method, 857 source clip, choosing a, 567–568 source files and applications (CD-ROM), 1111 source format for video, 1124–1126 source parameter (ScrollPane component), 1025 sources, color, 210–211 sources, comparing video, 1130 span of frames adding, 333–334 duration of, extending, 93 selecting, 93, 95 selecting multiple frames within, 93, 95 selecting single frames within, 93, 95 <span> tag, 949 Speech (Nellymoser), 477, 478 Speech sample rate setting, 499–500 speed coloring in character animation, 442
Spray Brush tool custom symbol spray pattern created with, 154–155 overview, 152–153 random spray pattern created with, 153–155 src attribute (embed tag), 715 stacking order changing, 293 overview, 293 stacking panels, 67 Stage area (Document window), 78–79 Stage View control (Document window), 79–80 stand-alone Flash Player described, 739–740 disadvantages of, 743 distribution of, 742 licensing of, 742 projector created using, 741–742 used to create projector, 741––742 Start Page, 60–62 Start Sync option, 486 Start value parameter (Tween class), 876 startDrag ( ) action, 801–802 startDrag method for MovieClip objects, 792 starter files, reviewing, 1056–1057 states input, 935 output, 936 overview, 934 for Pen tool, 120 send, 935–936 wait, 936 static text boxes creating, 237–238 expanding, 234 fixed-width, 234 overview, 233–235 static text options (Properties panel) anti-aliasing, 241 auto kerning, 241 fonts, choosing, 240 letter spacing, 241 paragraph formatting, 241–242 positioning text, 240 sizing text, 240 styles, choosing, 240 subscript, 241 superscript, 241
1175
S
S
Index
status displays, 89–90 status of game, checking, 1003–1006 Stearns, Geoff (SWFObject), 5, 707, 724 stop() action, 612–613 stop method for MovieClip objects, 793 Stop Sync option, 486 stopDrag method for MovieClip objects, 792 stopping sound, 487–491 storeProps function (Thumbnail class), 1096 storing animations in Graphic symbols, 373 in Movie clip symbols, 373 sound files, 480–481 storyboard for character animation, 428–429 Straighten mode (Pencil tool), 112 Straighten option (Selection tool), 135–136 stream sound overview, 486 stopping, 489–490 streaming files with Flash Media Server, 911 Strength setting filters, 388 strict typing in ActionScript 3.0, 826 string expressions, 763–764 operators, 768 string data type, 822 string literals for values, 762–763 strokes adjusting for, 221–222 adjusting transparency of, 221–222 color for, 123–124 Hairline line style, 127 Hatched line style, 127 height setting, 125 line styles, choosing, 124–127 lines compared, 124 Scale option, 127–129 Solid line style, 127 switching with Ink Bottle tool, 267–268 with Paint Bucket tool, 268–269 Strong easing type, 878 structure for project, establishing, 46–47 Stumpf, Felix (guest expert) examples from, 316, 332, 432 information on, 1114 tutorial: Using Video as a Basis for Fluid, HandDrawn Animation, 434–437
1176
style sheets applied to text fields, 955–958 creating, 955–956 loading into Flash movie, 956–958 subject matter for video, 1128–1130 subroutines, 777–778 Subselection tool, 121, 139–140 substituting fonts, 251–252 Subtract blend mode, 407 Sun AU, 475 supported HTML tags anchor tag, 949–950 bold tag, 948
carriage return tag, 948 font and paragraph styles, 948–949 tag, 948 tag, 949 tag, 949 tag, 949 tag, 949 italic tag, 948 tag, 949 overview, 948 paragraph tag, 948 <span> tag, 949 tag, 949 underline tag, 948 URL and ActionScript linking, 949–950 supporting audio and MP3 playback, 500 SVG (Scalable Vector Graphics), 25 S-VHS videotape, 1125 Swap button (Properties panel), 534 swapping bitmap graphics, 534 symbols, 182–183 Swatches panel custom color table, creating and loading, 216–218 custom color them loaded from Kuler panel, 214–215 custom GIF color palette, loading, 215–216 importing custom palettes, 214–218 options for, 213–214 overview, 211–213 .swf (Flash movie) files format overview, 10 overview, 8 playing, 10
Index
SWFObject creating HTML document with, 726–728 overview, 724 reviewing content with, 725–726 switch() statements, 771–772 switching fills with Ink Bottle tool, 267–268 with Paint Bucket tool, 268–269 strokes with Ink Bottle tool, 267–268 with Paint Bucket tool, 268–269 swLiveConnect attribute (embed tag), 716 symbol instances ActionScript used to control, 381–382 mask layers with, 419–420 reusing and modifying, 379–383 symbol timelines, moving tweens onto, 374–376 symbols. See also specific symbols adding, 354 Button symbols assigning a sound to a, 481–483 combining an action with an event handler to make a, 616–617 Down (press) state, adding sound to, 481–482 invisible buttons, 185, 619–625 Over (rollover) state, adding sound to, 482 overview, 175 testing, 190 using Graphic symbols in, 185–187 editing in Edit mode, 178 from library, 178–179 Main Timeline, returning to, 179 in new window, 178 overview, 284–285 in place, 178 font authortime, updating font symbols at, 255 creating, 253–255 overview, 252–253 in runtime shared libraries, 256–260 Graphic symbols importing video into, 568 Movie Clip symbols compared, 177, 373 overview, 174–175 storing animations in, 373
moved with 3D Translation tool, 292 Movie Clip symbols Graphic symbols compared, 177, 373 importing video into, 568 overview, 175 storing animations in, 373 native symbols button symbols, 175 components, 175 graphic symbols, 174–175 movie clip symbols, 175 overview, 174 nested structures for adding Movie Clip to Button symbol, 188–190 animating Graphic symbols in Movie Clip, 187–188 button, using Graphic symbols in, 185–187 converting raw shape into Graphic symbol, 183–184 modifying Movie Clip instance, 190–192 overview, 183 overview, 163 searches, 304 swapping, 182–183, 446–447 transformed with 3D Rotation tool, 288–292 Symmetry Brush effect (Deco tool), 156, 159–160 Synchronized Multimedia Integration Language (SMIL), 25–26 synchronizing motion tweening, 354 sound to animations, 485–486 syntax checking, 758 for creating event listeners, 1029 for declaring events, 987 PHP, 1053 system requirements (CD-ROM), 1110
T
tab order, changing, 77 target Flash Player version, choosing a, 567 Target object parameter (Tween class), 876 target object, replacing, 356 Target property parameter (Tween class), 876 technical questions, asking, 33
1177
T
T
Index
templates, 21, 84 temporary backgrounds in character animation, 442 terminal velocity in animation, 325 Test Movie command, 674–675 Test Scene command, 674–675 testing Button symbol, 190 Flash movies Bandwidth Profiler, using, 675–681 overview, 673–674 size report for, 681 with Test Movie command, 674–675 with Test Scene command, 674–675 site on real users, 43 text anti-aliasing, 233, 241, 964–971 attributes set in Properties panel, 240–246 auto kerning, 241 breaking apart, 294 converted to outlines, 548–549 dynamic text fields, 232, 235–236 editable text fields, 232, 235–236 editing, 284–285 filter effects for, 262–263 fonts, choosing, 240 graphic, 261–262 letter spacing, 241 manually editing overview, 260–261 scaling text, 261 sharing text attributes, 261 vector shapes, converting text into, 261–262 mask layers with, 420–423 metallic type, creating, 294–297 paragraph formatting, 241–242 pixel-based text scrolling with Movie Clips, 971–976 positioning text, 240 rendering properties, 963–971 scroll properties, 961–962 scrolling with TextArea component, 660–663 searches, 304 sizing text, 240 static text boxes expanding, 234 fixed-width, 234 overview, 233–235
1178
styles, choosing, 240 subscript, 241 superscript, 241 text rendering properties, 963–971 types of, 232–233 text fields creating, 990–993 dynamic, 932–934 dynamic text fields, 232, 235–236, 932–934 input, 930–932 text parameter (TextArea component), 1026 Text tool copying text with, 239 deleting text with, 238 editing with, 238–239 overview, 237 static text boxes, creating, 237–238 TextArea component condenseWhite parameter, 1026 editable parameter, 1026 enabled parameter, 1026 horizontalScrollPolicy parameter, 1026 how it works, 1027 htmlText parameter, 1026 maxChars parameter, 1026 overview, 1025 parameters, 1026 restrict parameter, 1026 text parameter, 1026 verticalScrollPolicy parameter, 1026 visible parameter, 1026 wordWrap parameter, 1026 textData instance, 1034 TextEvent.LINK event, 961 TextField class scroll properties, 961–962 text rendering properties, 963–971 TextField instances authortime, 964–966 overview, 954–955 runtime, 967–970 TextField object, image loaded into, 958–960 TextFormat object used for formatting fields, 954–955 tag, 949 TGA image files, 516 thickness:Number property, 963
Index
32-bit lossless source files, 535–536 3D properties, animating, 368–372 3D Rotation tool described, 286 symbols transformed with, 288–292 3D space overview, 286–287 perspective in, 287–288 vanishing point in, 287–288 3D transformations, enhancements to, 4 3D Translation tool described, 286 symbols moved with, 292 3D_rotationFlip.fla file, 370 3D_rotationReverse.fla file, 369 thumbHeight property (Gallery class), 1061 thumbnail button handlers, 1096–1099 Thumbnail class active property, 1078 clearTweens function, 1091 controlTweens function, 1091 creating, 1064–1066 dim function, 1091 imageData property, 1086–1087 mouse events enabled, within, 1097–1099 onThumbOut function, 1096 onThumbOver function, 1096 onTweenFinish function, 1091 saturation function, 1091 storeProps function, 1096 thumbnail holders in Gallery class, creating, 1066–1071 thumbnail image, loading, 1064–1066 thumbScript property (Gallery class), 1061 thumbURL property (Gallery class), 1061 TIFF image files, 517 tiling patterns with Deco tool, 158 time display, 86 time-based collisions, 839 Timeline Controller, 85–86 depth display, 87 display of frames, 86 editing frames, 90–96 editing layers, 96–98 expanding, 569 features of, 87–90 frame controls, 89
Frame View options, 98–100 layer controls, 88–89 Layer section, 85 moving, 85 onion skin, 89 opening, 85 overview, 84–85 resizing, 85 shortcut keys, 86 sound adding sound to a, 483–484 organizing sounds on a, 484–485 status displays, 89–90 time display, 86 Timeline/Frames section, 85 Timeline command, 152 Timeline Effects, 330 Timeline panel (Document window), 79 tint, 181 tinted frames, 99 toggle parameter (Button component), 1018 toggling grid, 83 rulers, 83 Tools panel. See also specific tools adding tools, 73–76 closing, 72 customizing, 72–73 hiding, 72 items in, 72 opening, 72 options for, 72 overview, 71 removing tools, 73, 76 sizing, 72 totalFrames property for MovieClip objects, 790 Trace Bitmap command, 538–539 tracing bitmaps, 299–300 transferring keyboard shortcuts, 71 Transform panel, 149–150, 283 transform property for MovieClip objects, 789 Transformation section (Motion Editor panel), 364 transitions in video, 1131 translating the solution into interactive language, 756–757
1179
T
T
Index
transparency bitmap graphics, 528–529 fills, adjusting for, 221–222 instances, 181 settings with gradients, 225–227 sliders for, 810–818 strokes, adjusting for, 221–222 trial versions, 1111 tricks for lip-syncing, 449–450 for Motion Editor panel, 364 tripods, use of, 1129 troubleshooting CD-ROM, 1111–1112 fonts, 250–251 Turner, Bill (guest expert) information on, 1114 tutorial: Lip-syncing, 450–454 tutorials Flash Character Design Strategies (Corsaro), 442–446 for lip-syncing, 450–454 online, 871 Using Video as a Basis for Fluid, Hand-Drawn Animation (Stumpf), 434–437 Tween class animating 3D properties, 880–881 back and forth, making an object move, 878–880 continueTo ( ) method, 882 Duration parameter, 877 Easing function parameter, 876, 877–878 End value parameter, 876 finish property, 882 help for, 875 mouse cursor, creating a graphic following the, 882–885 multiple instances, 882 overview, 875–876 position property, 882 Start value parameter, 876 Target object parameter, 876 Target property parameter, 876 Use seconds parameter, 877 tween layers graphics, adding, 354 graphics, pasting, 355
1180
keyframes, adding, 355 motion tweening, 354–355 symbols, adding, 354 tween spans animation, extending, 356 editing motion paths, 357–359 extending, 356 motion tweening, 354, 356 moving, 356 property keyframes, viewing, 356 target object, replacing, 356 tweened animation. See also shape tweening character animation motion guides, 447–448 overview, 446 panning, 446 symbol swapping, 446–447 classic motion tweens, 91 classic tweens, 339 described, 91 motion tweening classic tweens compared, 348–349 control added to animation along motion path, 359–360 creating motion tweens, 349–352 Ease values, 352 editing motion paths, 356–359 orienting, 354 overview, 348–349 presets, working with motion, 360–362 properties of, modifying, 352–354 rotating, 353 synchronizing, 354 tween layers, 354–355 tween spans, 354, 356 object-based motion tweens, 91 overview, 338–339 shape tweening creating a shape tween, 340–344 overview, 339–340 shape hints, adding, 344–347 shape tweens, 91 12-bit sound resolution, 1118 24-bit color, 206 24-bit lossless source files, 535–536
Index
type= “application/x-shock wave-flash” attribute (embed tag), 717 typeof operator used to check data types, 825 typography, 232
U
underline tag, 948 UILoader component, 1043–1044 UIScrollBar component direction parameter, 1027 how it works, 1028 overview, 1027 parameters, 1027–1028 scrollTargetName parameter, 1027–1028 visible parameter, 1028 unbalanced audio sources, 1127–1128 undefined data type, 825 Undo command, 151 units, changing, 83 unwanted noise, 1128 updates, 45 updateScroller function (Gallery class), 1075 updating shared assets, 926–928 symbols in multiple project files, 202 uploading scripts and images to your Web server, 1060–1061 URL and ActionScript linking, 949–950 for shared libraries, 924 URLLoader class, 766, 936, 945 usability design audience, defining, 39 character scenarios, creating, 39 competition, analyzing the, 40 content, structuring the, 40 goals and mission of site, defining, 38–39 “good design,” defining, 40 identifying factors of usability, 40–42 mockups of site, building, 43 testing site on real users, 43 Use seconds parameter (Tween class), 877 user comment form, creation of, 936–943
user input in Hangman game example interpreting, 1000–1003 overview, 1000 storing, 1007–1008 user-initiated collisions, 839 uses for Flash, list of examples for, 6
V
value parameter (RadioButton component), 1023 vanishing point in 3D space, 287–288 variables (ActionScript) array access operators, 764 case sensitivity of, 762 creating, 765–766 declaring action used to define variables, 766 HTML, establishing variables with, 767 loading variables from predefined source, 766 defined for animation, 312–316 expressions, 763–764 interactive form created with, 778–782 login sequence created with, 778–782 overview, 761–762 string literals for values, 762–763 VBR (Variable Bit Rate) MP3, 503–504 vector graphics bitmap caching (runtime), 550–551 bitmap graphics compared, 512–514 conversion from, 538–539 complex vector artwork, interpreting, 547–548 copying, 543 curves, optimizing, 549 Illustrator files, importing, 544–546 importing, 541–546 optimizing, 547–551 overview, 176, 511–514 pasting, 543 rules for, 540 text converted to outlines, 548–549 vector shapes, converting text into, 261–262 vector-based animator component of Flash CS4, 13 vector-based drawing program component of Flash CS4, 12
1181
V
V
Index
versions of ActionScript, 759–761 Versiown (Goldshell Digital Media), 749–750 || (vertical bars) as logical comparison operator, 769 verticalLineScrollSize parameter List component, 1022 ScrollPane component, 1025 verticalPageScrollSize parameter (List component), 1022 verticalScrollPolicy parameter List component, 1022 TextArea component, 1026 VHS videotape, 1124 VHS-C videotape, 1124 video Adobe Media Encoder CS4 Advanced settings, 565 advantages of, 560 Basic Audio settings, 565–566 Basic Video settings, 563–564 Bitrate settings, 564, 566 Crop tool, 566 Cue points section, 566 general export settings, 562 opening, 559 overview, 559–562 presets in, 561–562 audio compression in, 1132 audio track embedded in, 569 AVC/H.264 codec, 557–559, 911 AVI (Audio Video Interleaved) format, 1133 Betacam SP tape, 1125 CCD (charged-coupled device), 1126 CMOS, 1126 compression, 1132 compression artifacts, 1133 content, controlling, 570 cue points ActionScript, 582 creating, 582–594 embedded, 581–582 overview, 581–582 de-interlacing, 1132 deploying video files with Flash CS4, 570–575 Digital Betacam tape, 1125 Digital8 tape, 1125 DV (Digital Video stream) format, 1133 DVCAM tape, 1125 editing footage, 1131
1182
8mm videotape, 1124 embedded video content, formatting, 568–569 embedding video into a movie, 557 exposure, 1127 file size, 1131 files loaded into Flash movies, 911–916 filter effects, 1131 FLVPlayback component custom UI components, 578–581 overview, 575 parameters, 575–577 focus, locking, 1129 frame rate, 1132 frame size, 1131 HDV tape, 1125 Hi8 videotape, 1125 import format, choosing, 1131–1133 Import Video wizard formatting the embedded video content, 568–569 opening, 566 reviewing settings, 570 source clip, choosing a, 567–568 target Flash Player version, choosing a, 567 video content, controlling, 570 importing codec options for, 557–559 compressing video with Adobe Media Encoder CS4, 559–566 overview, 557 integration of, 556–557 loading a Flash video file at runtime, 556 miniDV tape, 1125 movement, avoiding quick and jerky, 1129 MPEG file recording, 1125 MPEG (Motion Picture Experts Group) format, 1133 native size, displaying a video at its, 916–921 NetStream object created to access Flash video content, 914–915 On2 VP6 codec, 557–559 On2 VP6-S codec, 911 optics, 1126 QT (Apple QuickTime) format, 1133 quality of, 1126–1127 real-time streaming a Flash video file at runtime, 556 recompression, 1133
Index
resizing, 563–564 sample_high.avi video file, 1130 sample_low.mpg video file, 1130 sample_mid.avi video file, 1130 searches, 304 shutter mechanism, 1127 sizing with metadata, 916–920 without metadata, 920–921 skin features, 572 Sorenson Spark codec, 557–559 sound quality with, 1127–1128 source format, 1124–1126 sources, comparing, 1130 streaming files with Flash Media Server, 911 subject matter for, 1128–1130 S-VHS videotape, 1125 tape quality, 1126 transitions, 1131 tripods, use of, 1129 VHS videotape, 1124 VHS-C videotape, 1124 white balance, 1129 WMV (Windows Media files) format, 1133 zooming, avoiding, 1129 video alpha channels keying, steps for, 594 live action footage, 594–597 overview, 594 video assets, 176 Video class height property, 916 videoHeight property, 916 videoWidth property, 916 width property, 916 video engine component of Flash CS4, 13 videoHeight property (Video class), 916 videoWidth property (Video class), 916 view property (GameController class), 986 viewpoints in animation, 319–321 Vine Fill effect (Deco tool), 156, 157 visible parameter Button component, 1018 CheckBox component, 1019 ComboBox component, 1020 List component, 1022 RadioButton component, 1023 ScrollPane component, 1025
TextArea component, 1026 UIScrollBar component, 1028 visible property for MovieClip objects, 789 Visio 2007 Bible (Wiley publication), 34 visual design, 979 visual hierarchy, 209–210 visual tricks commonly used in animation, 318 voices in character animation, 429–431 volume sliders, creating, 861–864
W
Wacom tablet, 116 wait state, 936 walk cycles in character animation, 437–441 waterfall model, 31 WAV (Windows Wave), 474 waveform, 92 Web browsers cross-browser consistency of bitmap graphics, 533 environment not needed for running movies, 22 support for ExternalInterface API, 729 support for plug-in version of Flash Player, 744–745 Web services, 27–28 Web Services Description Language (WSDL), 27 Web sites high expectations for, 17–20 Jack’s Page, 327 Processing, 327 Web-safe color, 206–207, 214 weight of objects in character animation, 432 while loops, 773–774 white balance video, 1129 white frames, 99 white space, 607 width attribute embed tag, 716 object tag, 709 width property for MovieClip objects, 789 Video class, 916 Window-Eyes (GW Micro), 665 windows, active, 68 Windows Bitmap files, 515 Windows Metafile files, 517
1183
W
W
Index
Windows platform color for, 206 interface fundamentals for Flash, 62–64 motion presets, 362 projector, creating, 703 Winkler, Tom (guest expert), 319, 322, 323, 326, 1114 with ( ) action (MovieClip objects), 795 w3JMail component, 937 wmode attribute embed tag, 716 object tag, 712–713 WMODE parameter, 22 WMV (Windows Media files) format, 1133 wordList property (GameModel class), 985 wordWrap parameter (TextArea component), 1026 workflow approving a final concept and budget, 38 assets, assembling, 44 concept, establishing, 32–38 documenting ideas in meetings, 32 Flash architecture, making the, 44 functional specification, 35–37 goals, establishing, 32–38 HTML page production, 44 local test environment, staging a, 44 maintenance, 45 organizational flowchart, 35 overview, 31–32 phase 1: preproduction, 32–43
1184
phase 2: production, 43–45 process flowchart, 35–36 quality assurance testing, 45 server test environment, staging a, 44–45 solution, producing a, 34–38 technical questions, asking, 33 updates, 45 World Wide Web Consortium (W3C), 25 WSDL (Web Services Description Language), 27
X
X property for MovieClip objects, 789 XFL files, 551–552 XML (eXtensible Markup Language) child nodes, 944–945 container tags, 944 Flash movie, loading XML document into a, 945–946 nodes, 944 overview, 24, 944–945 XML object, 945 XSL (eXtensible Stylesheet Language), 24
Y
Y property for MovieClip objects, 789
Z
Zoom tool, 79–80 zooming, avoiding, 1129
Wiley Publishing, Inc. End-User License Agreement READ THIS. You should carefully read these terms and conditions before opening the software packet(s) included with this book “Book”. This is a license agreement “Agreement” between you and Wiley Publishing, Inc. “WPI”. By opening the accompanying software packet(s), you acknowledge that you have read and accept the following terms and conditions. If you do not agree and do not want to be bound by such terms and conditions, promptly return the Book and the unopened software packet(s) to the place you obtained them for a full refund. 1. License Grant. WPI grants to you (either an individual or entity) a nonexclusive license to use one copy of the enclosed software program(s) (collectively, the “Software”) solely for your own personal or business purposes on a single computer (whether a standard computer or a workstation component of a multi-user network). The Software is in use on a computer when it is loaded into temporary memory (RAM) or installed into permanent memory (hard disk, CD-ROM, or other storage device). WPI reserves all rights not expressly granted herein. 2. Ownership. WPI is the owner of all right, title, and interest, including copyright, in and to the compilation of the Software recorded on the physical packet included with this Book “Software Media”. Copyright to the individual programs recorded on the Software Media is owned by the author or other authorized copyright owner of each program. Ownership of the Software and all proprietary rights relating thereto remain with WPI and its licensers. 3. Restrictions on Use and Transfer. (a) You may only (i) make one copy of the Software for backup or archival purposes, or (ii) transfer the Software to a single hard disk, provided that you keep the original for backup or archival purposes. You may not (i) rent or lease the Software, (ii) copy or reproduce the Software through a LAN or other network system or through any computer subscriber system or bulletin-board system, or (iii) modify, adapt, or create derivative works based on the Software. (b) You may not reverse engineer, decompile, or disassemble the Software. You may transfer the Software and user documentation on a permanent basis, provided that the transferee agrees to accept the terms and conditions of this Agreement and you retain no copies. If the Software is an update or has been updated, any transfer must include the most recent update and all prior versions. 4. Restrictions on Use of Individual Programs. You must follow the individual requirements and restrictions detailed for each individual program in the “Using the CD-ROM” appendix of this Book or on the Software Media. These limitations are also contained in the individual license agreements recorded on the Software Media. These limitations may include a requirement that after using the program for a specified period of time, the user must pay a registration fee or discontinue use. By opening the Software packet(s), you agree to abide by the licenses and restrictions for these individual programs that are detailed in the “Using the CD-ROM” appendix and/or on the Software Media. None of the material on this Software Media or listed in this Book may ever be redistributed, in original or modified form, for commercial purposes.
5. Limited Warranty. (a) WPI warrants that the Software and Software Media are free from defects in materials and workmanship under normal use for a period of sixty (60) days from the date of purchase of this Book. If WPI receives notification within the warranty period of defects in materials or workmanship, WPI will replace the defective Software Media. (b) WPI AND THE AUTHOR(S) OF THE BOOK DISCLAIM ALL OTHER WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, WITH RESPECT TO THE SOFTWARE, THE PROGRAMS, THE SOURCE CODE CONTAINED THEREIN, AND/OR THE TECHNIQUES DESCRIBED IN THIS BOOK. WPI DOES NOT WARRANT THAT THE FUNCTIONS CONTAINED IN THE SOFTWARE WILL MEET YOUR REQUIREMENTS OR THAT THE OPERATION OF THE SOFTWARE WILL BE ERROR FREE. (c) This limited warranty gives you specific legal rights, and you may have other rights that vary from jurisdiction to jurisdiction. 6. Remedies. (a) WPI’s entire liability and your exclusive remedy for defects in materials and workmanship shall be limited to replacement of the Software Media, which may be returned to WPI with a copy of your receipt at the following address: Software Media Fulfillment Department, Attn.: Flash CS4 Professional Bible, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, or call 1-800-762-2974. Please allow four to six weeks for delivery. This Limited Warranty is void if failure of the Software Media has resulted from accident, abuse, or misapplication. Any replacement Software Media will be warranted for the remainder of the original warranty period or thirty (30) days, whichever is longer. (b) In no event shall WPI or the author be liable for any damages whatsoever (including without limitation damages for loss of business profits, business interruption, loss of business information, or any other pecuniary loss) arising from the use of or inability to use the Book or the Software, even if WPI has been advised of the possibility of such damages. (c) Because some jurisdictions do not allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation or exclusion may not apply to you. 7. U.S. Government Restricted Rights. Use, duplication, or disclosure of the Software for or on behalf of the United States of America, its agencies and/or instrumentalities “U.S. Government” is subject to restrictions as stated in paragraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause of DFARS 252.227-7013, or subparagraphs (c) (1) and (2) of the Commercial Computer Software - Restricted Rights clause at FAR 52.227-19, and in similar clauses in the NASA FAR supplement, as applicable. 8. General. This Agreement constitutes the entire understanding of the parties and
revokes and supersedes all prior agreements, oral or written, between them and may not be modified or amended except in a writing signed by both parties hereto that specifically refers to this Agreement. This Agreement shall take precedence over any other documents that may be in conflict herewith. If any one or more provisions contained in this Agreement are held by any court or tribunal to be invalid, illegal, or otherwise unenforceable, each and every other provision shall remain in full force and effect.
Spine: 1.63"
CD-ROM Included
The CD includes all of the source files for the step-by-step exercises in the book. You’ll also find custom components for image loading and effects. System Requirements: See the CD Appendix in the book for details and complete system requirements.
Robert Reinhardt is one of the world’s leading Flash experts, and is co-founder of [the Makers], a multimedia design, consulting, and training company based in Portland, Oregon.
has worked with Flash since 1999, creating compelling online and print brand identities for independent companies, including artists, filmmakers, and architects.
www.wiley.com/go/compbooks
Link a series of elements with Inverse Kinematics (IK)
®
What’s on the CD-ROM?
Snow Dowd
Auto-create patterns with the new Deco tool
Adobe
®
Understand the Flash CS4 user interface and tools Use filters, effects, masks, and layers to add impact Master special techniques for animating characters Unravel the nuts and bolts of ActionScript 3.0 code Add video or MP3 audio to Flash movies Create a game in Flash and win
Flash CS4 Professional
• • • • • •
Use the stand-alone projector to play Flash movies
Shelving Category: COMPUTERS / Internet / Web Page Design Reader Level: Beginning to Advanced
$49.99 USA $59.99 Canada
Full-Color Insert
• Exercise example files • ActionScript 3.0 code samples and more
• Sixteen-page full-color insert with cutting-edge examples
Robert Reinhardt and Snow Dowd
Deliver winning Flash content with this one-stop guide Make Web pages that really pop with the powerful new Adobe Flash CS4 Professional and the latest edition of this top-selling guide by two of the savviest Flash experts around. Robert Reinhardt and Snow Dowd know all the secrets, and they take you under the hood, from Flash basics to advanced techniques. Design a game, learn ActionScript code, drop in movie clips, and more—this book is packed with over a thousand pages of step-by-step tutorials, expert tips, and practical examples.
CD-ROM Included!
Reinhardt Dowd
Adobe
®
Flash CS4 ®
Professional Become f luent in the Flash workspace Master ActionScript and build a game
®
Integrate XML data with Flash movies
The book you need to succeed!