Chapter 27. Interacting with Movie Clips

IN THIS CHAPTER

  • Defining collisions

  • Using the hitTest() method

  • Using the ColorTransform class

  • Accessing the Sound class

  • Controlling the volume and balance of a sound

  • Printing Flash content with the PrintJob class

This chapter continues your exploration of the MovieClip class in ActionScript. You explore the ins and outs of collision detection for MovieClip objects and learn how to control the visibility of the mouse pointer or to attach a custom cursor to the mouse pointer. You look at other ActionScript elements such as ColorTransform and Sound objects that work with MovieClip objects to create visual and audio effects, respectively.

Tip

Flash Player 8 introduced the ColorTransform class, which enables you to more easily apply color effects to your MovieClip objects. You can continue to use this class in ActionScript 2 targeted for Flash Player 9.

You will also learn how to print Flash content with the PrintJob class, introduced with Flash Player 7. The Flash Player creates high-quality output for hard copy artwork.

Movie Clip Collision Detection

Have you ever wanted to detect the intersection of two elements in a Flash movie? If two Movie Clip instances overlap on the Stage, how would you know? How would you tell ActionScript to look for an overlap? In ActionScript, there are two primary types of intersections (or collisions):

  • User-initiated collisions: This type of intersection occurs when you click and drag an object (a MovieClip object) and overlap another MovieClip object as you drag or release. You can also consider the mouse pointer an "object" that can intersect with another object. For example, if you move the mouse pointer over a MovieClip object, you can detect when the mouse pointer enters the space of the MovieClip object.

  • Script- or time-based collisions: This type of intersection between objects happens when randomly moving objects collide with one another, such as balls bouncing around the Stage, detecting the edges of the frame, and responding to other boundaries or objects.

In this section, you look at examples in each of these categories. Let's begin with a quick review of the _droptarget property of the MovieClip object.

Using _droptarget

A collision between two MovieClip objects can occur if the user drags one Movie Clip instance to the location of another Movie Clip instance. We first examined the startDrag() action and method in Chapter 25, "Controlling Movie Clips." In the dog movie, you used the _droptarget property of a MovieClip object to detect whether the area of one MovieClip object occupied the area of another MovieClip object. To recap, you can test the intersection of two Movie Clips with the following code:

var mc_1:MovieClip;
var mc_2:MovieClip;
mc_1.onPress = function():Void {
 this.startDrag();
};
mc_1.onRelease = mc_1.onReleaseOutside = function():Void {
 trace(eval (this._droptarget));
 if(eval(this._droptarget) == mc_2){
   trace("this MC overlaps mc_2");
 } else {
   trace("this MC does NOT overlap mc_2");
 }
 stopDrag ();
}

This code could occur on a MovieClip object named mc_1. When the user clicks the MovieClip instance, the MovieClip.startDrag() method is invoked, and the user can drag the Movie Clip instance on the Stage. When the user releases the mouse, the _droptarget property (which returns target paths in slash syntax) is evaluated to convert the target path to dot syntax. If the _droptarget property returns the path to another instance, the if condition sees whether the path matches mc_2. If the paths match, the trace() action indicating an overlap is executed. Otherwise, a separate trace() action notifies you that the instance is not on top of mc_2.

Collision detection with hitTest()

You can also perform more advanced collision detection using the hitTest() method of the MovieClip object. hitTest() does exactly what it says—it tests to see whether a "hit" occurred between two elements. hitTest() has the following two formats:

mc.hitTest(anotherInstance);

or

mc.hitTest(x coordinate, y coordinate, shapeFlag);

With this method, you can determine whether the X and Y coordinates are within the space occupied by the Movie Clip instance. You can use onClipEvents such as mouseMove or newer event handlers such as onMouseMove() to check constantly for a hit occurrence:

onClipEvent(mouseMove){
 if(this.hitTest(_root._xmouse, _root._ymouse, true)){
  trace("A hit has occurred");
 }
}

or

mc.onMouseMove = function(){
 if(this.hitTest(_root._xmouse, _root._ymouse, true)){
  trace("A hit has occurred");
 }
};

This code reports a trace() action anytime the mouse pointer is moved within the artwork of the Movie Clip instance to which the onClipEvent or onMouseMove() handler is attached. The shape flag attribute of hitTest() defines the actual test area for the hit. If the shape flag is set to true, a hit occurs only if the X and Y coordinates occur within the actual artwork of the Movie Clip instance. If the shape flag is set to false, a hit occurs whenever the X and Y coordinates occur within the bounding box of the Movie Clip instance. In Figure 27.1, if the left circle uses a shape flag of true, a hit is reported whenever the X and Y coordinates occur within the shape of the circle (not within the bounding box). If the right circle uses a shape of false, a hit is reported when the X and Y coordinates occur within the bounding box.

The shape flag determines the boundary of the Movie Clip instance for the hitTest() method.

Figure 27.1. The shape flag determines the boundary of the Movie Clip instance for the hitTest() method.

Note

You can see a working example of shape flags and the hitTest() method in the hitTest_xy.fla file, located in the ch27 folder of this book's CD-ROM. Open this Flash document, and test the movie. As you move your mouse within the space of each object, you will notice that the hit area is different for each object. You create your own Flash movie that uses hitTest() in our coverage of the Mouse class in this chapter.

The other format for the hitTest() method is to simply specify a target path to compare for a hit occurrence. With this syntax, you cannot use a shape flag option; if any area of the bounding box for a Movie Clip instance touches the bounding box of the tested instance, a hit occurs. For example, you can modify the ActionScript used earlier to indicate a hit between instances, instead of X and Y coordinates:

onClipEvent(mouseMove){
 if(this.hitTest(mc_2)){
trace("A hit has occurred.");
 }
}

or

mc_1.onMouseMove = function(){
 if(this.hitTest(mc_2)){
  trace("A hit has occurred.");
 }
};

This code assumes that other actions are actually initiating a startDrag() action. Also, we have omitted the other half of the if condition in both this example and the previous example. If you omit a condition operator and test condition, ActionScript assumes that you are testing for a true result (as a Boolean value). The following if conditions are exactly the same:

var myMouseClick:Boolean = true;
if(myMouseClick){
 trace("myMouseClick is true.");
}
if(myMouseClick == true){
 trace("myMouseClick is true.");
}

Therefore, to test for a true value with any if statement, specify the variable (or method) that has a Boolean value. The hitTest() method yields either a true (a hit has occurred) or a false (no hit has occurred) result. Note that, with scripting languages, it is more common to use the former example for testing true conditions.

Note

You can see a working example of targets and the hitTest() method in the hitTest_target.fla file, located in the ch27 folder of this book's CD-ROM. You will create a Flash movie that uses this type of hitTest() method in our coverage of the Sound class later in this chapter.

Using the Mouse Class

With ActionScript, you can emulate custom mouse pointers (that is, the graphic shown for the mouse pointer) by using the startDrag() behavior (with lock to center true) on Movie Clips containing icon graphics. However, this technique does not hide the original mouse pointer—it appears directly above the dragged Movie Clip instance. ActionScript features a static Mouse class, which has the following two simple methods:

  • show(): This method reveals the mouse pointer. By default, the mouse pointer appears at the start of a movie.

  • hide(): This method turns off the mouse pointer's visibility. To reveal the mouse pointer again, execute the show() method.

Once the Mouse object (that is, the mouse pointer) is hidden, you can lock a MovieClip object containing a new icon graphic to the position of the mouse pointer. In this section, you create a Flash movie with a large circle MovieClip object. When the mouse pointer moves into the area of this object, you attach a smaller circle to the mouse pointer's position. The hitTest() method will be used to determine when the mouse pointer moves into the area of the large circle, and the attachMovie() method of the MovieClip object will affix the small circle to the mouse pointer's position.

  1. Create a new Flash document (Ctrl+N or

    Using the Mouse Class
  2. Select the Oval tool and draw a circle. In the Property inspector, set the circle's size to 25 × 25.

  3. With the circle artwork selected, press the F8 key to convert the artwork into a Movie Clip symbol. Name the symbol circleClip.

  4. Name the instance on the Stage circle_big in the <Instance Name> field of the Property inspector. Increase the size of this particular instance to 200 × 200, and apply a Tint effect to fill the instance with a different solid color. Center the instance on the Stage using the Align panel.

  5. Now you have to link the circleClip symbol in the Library panel to the exported Flash movie file (.swf). Right-click (Control+click on the Mac) the circle symbol, and choose Linkage. Select the Export for ActionScript check box, and the Identifier field auto-fills with the text circleClip, as shown in Figure 27.2. Click OK to accept these settings.

    The circle symbol is now linked to the Flash movie.

    Figure 27.2. The circle symbol is now linked to the Flash movie.

    After the circle symbol is linked, you can dynamically insert the symbol into the Flash movie with ActionScript. Remember that you want to attach the circle to the mouse pointer when it enters the space of the circle_big instance.

  6. On the Main Timeline (that is, Scene 1), create a new layer and name it actions. Select frame 1 of this layer, and open the Actions panel. Type the code shown in Listing 27.1 into the Script pane as follows. Do not type the

    The circle symbol is now linked to the Flash movie.

    Tip

    Any code listings, such as Listing 27.1, are available on this book's CD-ROM, in the respective chapter folder. Listing files are .as files, so you can even use the #include directive to just add the listing's code to your .fla file.

    Example 27.1. The onMouseMove() Handler for the circle_big Instance

    1.  var circle_big:MovieClip;
    2.
    3.  circle_big.onMouseMove = function():Void {
    4.     if (this.hitTest(_root._xmouse, _root._ymouse, true)) {
    5.        var mc:MovieClip = !(circle_sm instanceof MovieClip) ? 
    The onMouseMove() Handler for the circle_big Instance
    _root.attachMovie("circleClip", "circle_sm", 1) : circle_sm; 6. mc._x = _root._xmouse; 7. mc._y = _root._ymouse; 8. Mouse.hide(); 9. updateAfterEvent(); 10. } else { 11. if(circle_sm instanceof MovieClip) circle_sm.removeMovieClip(); 12. Mouse.show(); 13. } 14. };

    Here, you use the event handler onMouseMove() for MovieClip objects. This handler is assigned to the circle_big in line 3. When the mouse moves in the Flash movie, the function(){} code executes in lines 4 through 14.

    If the X and Y positions of the mouse pointer intersects with the circle_big instance, the if condition in line 4 executes. Line 5 checks to see if the new graphic (that is, the circleClip symbol in the Library) exists in the movie. If it doesn't, the symbol is attached to the Main Timeline (_root) in line 5 as well. The new instance is named circle_sm.

    Note

    For more information on the ?: conditional operator, search for the phrase "?: conditional operator" in the Flash Help panel (Help

    The onMouseMove() Handler for the circle_big Instance

    Lines 6 and 7 position the X and Y coordinates of the circle_sm instance by referencing the current position of the mouse pointer (_root._xmouse and _root._ymouse). Line 8 hides the mouse pointer icon, while line 9 uses the updateAfterEvent() function to force a video refresh of the Flash movie. This enables the circle_sm to move very smoothly across the Stage.

    Lines 10 through 13 execute if the mouse pointer is not within the space of the circle_big instance. Line 11 checks to see if circle_sm exists in the movie—if it does, it is removed. The mouse pointer reappears when the mouse moves outside of the circle_big instance (line 12).

  7. Save your Flash document as mouse_hitTest.fla, and test it (Ctrl+Enter or

    The onMouseMove() Handler for the circle_big Instance
    The left image shows the mouse outside the large circle, whereas the right image shows the mouse inside the large circle with the small circle attached.

    Figure 27.3. The left image shows the mouse outside the large circle, whereas the right image shows the mouse inside the large circle with the small circle attached.

That might seem like a lot of work to hide a mouse pointer, but in the process, you have learned how to attach your own icons to the mouse pointer. You can use this same methodology to add any custom graphic to the mouse pointer. Simply add a different linked symbol to the Library, and change the linkage ID in the attachMovie() method.

Note

You can find the completed example, mouse_hitTest.fla, in the ch27 folder of this book's CD-ROM.

Manipulating Color Attributes

The ColorTransform class in ActionScript gives you unprecedented control of the appearance of your MovieClip objects. By controlling the color (and transparency) of your artwork with ActionScript's ColorTransform class, you can:

  • Create on-the-fly color schemes or "skins" for Flash interfaces.

  • Enable users to select and view color preferences for showcased products on an e-commerce site.

  • Instantly change the color attributes of a Flash design-in-progress for a client.

Because color is controlled through the ColorTransform class, we'll quickly review the unique properties within this class. Refer to Table 27.1 for more information. Note that this table is organized by order of practical use.

Warning

The ColorTransform class requires Flash Player 8 or higher. The older Color class for Flash Player 5 and higher is officially deprecated in Flash Player 8. If you need to control the color of MovieClip instances in Flash Player 7 or earlier movies, use the Color class instead. You can read our archived coverage of the Color class from the Macromedia Flash MX 2004 Bible (Wiley, 2004) at www.flashsupport.com/archive.

Table 27.1. Properties for the ColorTransform Class

Property

Definition

Options

rgb

Retrieves or sets the RGB offset for the targeted Movie Clip. This property changes all colors in the targeted instance to one solid RGB color.

ct.rgb = 0xRRGGBB;

where:

ct is the name of the ColorTransform object. We'll discuss the creation of ColorTransform objects in this section. RR, GG, and BB are the offset values (in hexadecimal) for the Red, Green, and Blue channels, respectively.

[Channel]Multiplier

Retrieves or sets the multiplier used by a specific color channel in the targeted Movie Clip. Acceptable values are between (and including) −1 and 1. You can preview a channel's multiplier effect by using the left-hand column of values in the Advanced Effect dialog box of the Color mode, as accessed in the Property inspector settings for a Movie Clip instance.

ct.redMultiplier = 0.2;

ct.greenMultiplier = 0.65;

ct.blueMultiplier = −1;

ct.alphaMultiplier = 0.1;

where:

ct is the name of a ColorTransform object. We'll discuss the intricacies of these properties in the following sections.

[Channel]Offset

Retrieves or sets the offset used by a specific color channel in the targeted Movie Clip. Acceptable values are between (and including) −255 and 255. You can preview a channel's offset effect by using the left-hand column of values in the Advanced Effect dialog box of the Color mode, as accessed in the Property inspector settings for a Movie Clip instance.

ct.redOffset = 100;

ct.greenOffset = 50;

ct.blueOffset = 25;

ct.alphaOffset = 0;

where:

ct is the name of a ColorTransform object. You'll practice the use of offsets in an exercise within this section.

Creating a ColorTransform object

To manipulate the color attributes of a Movie Clip instance, you need to create a new ColorTransform object that references the Movie Clip instance. In the following steps, you learn to use the constructor for the ColorTransform object. Let's work out the steps required to take control of color properties.

Note

For the exercises with the Color object, make a copy of the dogColor_starter.fla document in the ch27 folder of this book's CD-ROM. Thank you, Sandro Corsaro, of www.sandrocorsaro.com, for supplying the dog artwork!

  1. Save the starter file as dogColor_100.fla.

  2. Select the instance of the dog graphic on the Stage. Open the Property inspector and name this Movie Clip instance dog_1.

  3. Create a new layer on the Main Timeline, and name the layer buttons.

  4. Open the Components panel and drag an instance of the Button component onto the Stage. Place the instance near the left corner of the Stage. We discuss components in more detail in Chapter 33, "Using Components." For now, we guide you through the use of this component for the purposes of this exercise.

  5. Select the Button component instance on the Stage, and open the Property inspector. Make sure the Parameters tab is selected in the inspector. Name this instance redButton. Type the text Red in the label field. Refer to the settings shown in Figure 27.4.

    The parameters for this instance of the Button component

    Figure 27.4. The parameters for this instance of the Button component

  6. Now you need to create a changeColor() function in the movie. This function is executed by the redButton instance when the button is clicked. Create a new layer on the Main Timeline and name it actions. Select frame 1 of the actions layer, and open the Actions panel (F9, or Option+F9 on the Mac). Type the following code into the Script pane:

    1.  import flash.geom.ColorTransform;
    2.
    3.  var dog_1:MovieClip;
    4.  var redButton:mx.controls.Button;
    5.
    6.  redButton.addEventListener("click", changeColor);
    7.
    8.  function changeColor(evt:Object):Void {
    9.     var label:String = evt.target.label.toLowerCase();
    10.    if (label == "red") {
    11.       var ct:ColorTransform = new ColorTransform();
    12.       ct.rgb = 0xFF0000;
    13.       dog_1.transform.colorTransform = ct;
    14.    }
    15. }

    Line 1 imports the ColorTransform class so that the ActionScript compiler can correctly create the Flash movie on publish. Lines 3 and 4 declare the data types of the dog_1 and redButton instances, respectively.

    Line 6 tells the redButton instance to register the changeColor() function as a listener for click events. Whenever the redButton instance is clicked, the changeColor() function is invoked.

    The changeColor() function is defined on lines 8 through 15. In this function, the evt argument represents an event object that the Button instance passes to the function. When the redButton instance is clicked, evt.target will equal redButton. (You'll be adding another instance in short order.) Line 9 of this function establishes a local variable named label that returns the label text inside of the target instance and converts the label text to lowercase. If label equals "red" in line 10, lines 11 through 13 will execute. Line 11 creates a new ColorTransform object called ct. Once the ct object is initiated, you can access properties of the ColorTransform object, such as rgb. In line 10, you set the color to pure red, designated by 0xFF0000 in hexadecimal. In line 13, you apply the ct instance to the colorTransform property of the MovieClip.transform property.

  7. Save the Flash document, and test the movie. Click the redButton instance on the Stage. The color of the dog_1 Movie Clip should change to bright red. Close the Flash movie and return to the Flash CS3 authoring environment.

  8. To see that rgb is both a property you can write and read, let's create some trace() messages for the Output panel. Go back to the changeColor() function on frame 1. Add the following line of code just before the closing curly brace ( } ) of the if() action. Type this as one line of code:

    trace("ct's RGB numeric value = " + ct.rgb);
  9. Save the document and test the movie. When you click the redButton instance, the Output panel opens and displays the following text:

    ct's RGB numeric value = 16711680
  10. To change this value back to the hexadecimal value you entered in the rgb property, you need to convert the value to base 16. Add the following action after the last trace() action from Step 8:

    trace("ct's RGB hex value = " + ct.rgb.toString(16));
  11. Save the document and test the movie. When you click the redButton instance, the Output panel should open and display the new value:

    ct's RGB numeric value = 16711680
    ct's RGB hex value = ff0000

    However, you won't need to convert rgb's native return value to set another ColorTransform object equal to a previous rgb value. In the following steps, you will create another dog and ColorTransform object team.

  12. Duplicate the dog_1 Movie Clip instance on the Stage (Edit

    The parameters for this instance of the Button component
  13. Duplicate the Button component instance on the Stage, and position the new instance below the original one. In the Property inspector, change its instance name to passRedButton. Change its label value to Pass Red.

  14. Select frame 1 of the actions layer, and open the Actions panel. On the closing curly brace line of the existing if() code in the changeColor() function, add the code shown in bold in Listing 27.2. Also, add the new variables shown in bold formatting at the top of the listing.

    Example 27.2. Checking for the Pass Red Label

    import flash.geom.ColorTransform;
    
    var dog_1:MovieClip;
    var dog_2:MovieClip;
    var redButton:mx.controls.Button;
    var passRedButton:mx.controls.Button;
    
    redButton.addEventListener("click", changeColor);
    passRedButton.addEventListener("click", changeColor);
    
    function changeColor(evt:Object):Void {
       var label:String = evt.target.label.toLowerCase();
       if (label == "red") {
          var ct:ColorTransform = new ColorTransform();
          ct.rgb = 0xFF0000;
          dog_1.transform.colorTransform = ct;
          trace("ct's RGB numeric value = " + ct.rgb);
          trace("ct's RGB hex value = " + ct.rgb.toString(16));
       } else if (label == "pass red") {
          var ct:ColorTransform = new ColorTransform();
          ct.rgb = dog_1.transform.colorTransform.rgb;
          dog_2.transform.colorTransform = ct;
       }
    }

    Tip

    For this example, we wanted to demonstrate the reading and writing of the rgb property. You can also simply pass the transform property, which includes the MovieClip instance's alpha value, to another MovieClip object:

    dog_2.transform.colorTransform = dog_1.transform.colorTransform;
  15. Save the Flash document and test the movie. When you click the redButton instance, the dog_1 Movie Clip instance turns red. When you click the passRedButton instance, the dog_2 Movie Clip instance turns red.

Note

If you click the second Button instance first, the dog_2 Movie Clip instance will turn black. Why? Because the first button's actions were not executed, and there was no previous rgb property value for the new rgb property. Consequently, ActionScript returns a zero value. In hexadecimal color, zero is equivalent to black.

Now that you've had some experience with the ColorTransform object's rgb property, let's move on to a more complex use of ColorTransform. You'll use the Flash document from this exercise, so keep the dogs on the Stage!

Note

You can find the completed Flash document, dogColor_100.fla, in the ch27 folder of this book's CD-ROM.

Setting multiplier and offset values

The ColorTransform class also features multiplier and offset properties, which require a more thorough understanding of RGB color space.

The multiplier and offset properties of the ColorTransform class are

  • redMultiplier—The Red channel percentage

  • redOffset—The Red channel offset

  • greenMultiplier—The Green channel percentage

  • greenOffset—The Green channel offset

  • blueMultiplier—The Blue channel percentage

  • blueOffset—The Blue channel offset

  • alphaMultiplier—The Alpha channel percentage

  • alphaOffset—The Alpha channel offset

The multiplier properties are decimal values, ranging in value from −1 to 1. The offset properties are integer-based from −255 to 255 (derived from 24-bit RGB color space, in which each 8-bit color channel can have a range of 256 values).

These properties and values may seem complex, so refer to the Advanced options of the Color menu for symbol instances in the Property inspector for guidance. With the Advanced option chosen in the Color menu, click the Settings button. In the Advanced Effect dialog box, the left-hand color controls are percentage-based (or multipliers), whereas the right-hand controls are offset-based. Admittedly, color is difficult to visualize from numbers. To accurately predict the color changes with ColorTransform, we use the Advanced Effect dialog box to help us out.

Note

Make a copy of the dogColor_100.fla file if you didn't complete the previous section's exercise. This document is located in the ch27 folder of this book's CD-ROM.

  1. Resave the Flash document from the previous section as dogColor_200.fla.

  2. Select the original dog_1 Movie Clip instance on the Stage. Open the Property inspector, and choose the Advanced option in the Color menu. Press the Settings button to the right of the menu. In the Advanced Effect dialog box, enter the following value on the left-hand side: −100% Blue. On the right-hand side, enter these values: 37 G and 255 B. Refer to Figure 27.5. Click OK to close the dialog box. With these values, the dog_1 instance should be a monochrome blue with yellow eyes. Normally, you would want to write these values down so that you had them to use later. Because you have them printed here in this book, erase them by choosing None from the Color menu in the Property inspector. The dog_1 instance should now appear in its original state.

    These settings will change the color of the dog_1 instance.

    Figure 27.5. These settings will change the color of the dog_1 instance.

  3. Duplicate one of the existing Button component instances on the Stage. Place the duplicated instance underneath the last Button component instance. Name the instance rabidButton. Change the label value to Rabid.

    With this new instance, you will create some code that will initiate a new ColorTransform object. The new object will be given properties that have the same values as those determined in Step 2.

  4. Select frame 1 of the actions layer and open the Actions panel (F9, or Option+F9 on the Mac). Add the bold code shown in Listing 27.3.

    Example 27.3. Checking for the rabid Label

    import flash.geom.ColorTransform;
    
    var dog_1:MovieClip;
    var dog_2:MovieClip;
    var redButton:mx.controls.Button;
    var passRedButton:mx.controls.Button;
    var rabidButton:mx.controls.Button;
    
    redButton.addEventListener("click", changeColor);
    passRedButton.addEventListener("click", changeColor);
    rabidButton.addEventListener("click", changeColor);
    
    function changeColor(evt:Object):Void {
       var label:String = evt.target.label.toLowerCase();
       if (label == "red") {
          var ct:ColorTransform = new ColorTransform();
          ct.rgb = 0xFF0000;
          dog_1.transform.colorTransform = ct;
          trace("ct's RGB numeric value = " + ct.rgb);
          trace("ct's RGB hex value = " + ct.rgb.toString(16));
       } else if (label == "pass red") {
          var ct:ColorTransform = new ColorTransform();
          ct.rgb = dog_1.transform.colorTransform.rgb;
          dog_2.transform.colorTransform = ct;
       } else if (label == "rabid"){
          var ct:ColorTransform = new ColorTransform();
          ct.blueOffset = 255;
          ct.blueMultiplier = −1;
          ct.greenOffset = 37;
          dog_1.transform.colorTransform = ct;
       }
    }

    In the preceding code, you created a new ColorTransform instance named ct. In addition to rgb, ColorTransform instances can have offset and multiplier values for each color (and alpha) channel. In Listing 27.3, you assigned the values you determined in Step 2. Offset values have a one-to-one relationship with the offset values displayed in the Advanced Effect dialog box, but multiplier values are divided by 100. So, if you have a multiplier value of −100 in the Advanced Effect dialog box, the equivalent ColorTransform multiplier value would be −1. After you have set the appropriate offset and/or multiplier values, you apply the ct instance to the colorTransform property of the transform property of the dog_1 instance.

    Note

    The ColorTransform class is one of two types of alterations to Movie Clips that can be made with the Transform class. The transform property of the MovieClip class uses the Transform class, which is available in Flash Player 8 (and higher) and encompasses a wide range of characteristics that can be applied to the MovieClip class. For more detailed information of the Transform class, refer to the Flash Help panel.

  5. Save the Flash document, and test the movie. Click the new Button instance that you added in Step 3. The colors of the dog_1 Movie Clip instance should change to match those you saw in Step 2. Close the Test Movie window, and return to the Flash CS3 authoring environment.

    Now you will create a button that restores the original look of the dog_1 Movie Clip instance.

  6. Duplicate one of the Button instances, and place the new instance underneath the last Button instance. In the Property inspector, name this component instance restoreButton. Change the label value to Restore.

  7. Select frame 1 of the actions layer, and open the Actions panel (F9, or Option+F9 on the Mac). Add the bold code shown in Listing 27.4 to the Script pane.

    Example 27.4. Checking for the Restore Label

    import flash.geom.ColorTransform;
    
    var dog_1:MovieClip;
    var dog_2:MovieClip;
    var redButton:mx.controls.Button;
    var passRedButton:mx.controls.Button;
    var rabidButton:mx.controls.Button;
    var restoreButton:mx.controls.Button;
    
    
    redButton.addEventListener("click", changeColor);
    passRedButton.addEventListener("click", changeColor);
    rabidButton.addEventListener("click", changeColor);
    restoreButton.addEventListener("click", changeColor);
    
    
    function changeColor(evt:Object):Void {
       var label:String = evt.target.label.toLowerCase();
       if (label == "red") {
          var ct:ColorTransform = new ColorTransform();
          ct.rgb = 0xFF0000;
          dog_1.transform.colorTransform = ct;
          trace("ct's RGB numeric value = " + ct.rgb);
    trace("ct's RGB hex value = " + ct.rgb.toString(16));
       } else if (label == "pass red") {
          var ct:ColorTransform = new ColorTransform();
          ct.rgb = dog_1.transform.colorTransform.rgb;
          dog_2.transform.colorTransform = ct;
       } else if (label == "rabid"){
          var ct:ColorTransform = new ColorTransform();
          ct.blueOffset = 255;
          ct.blueMultiplier = −1;
          ct.greenOffset = 37;
          dog_1.transform.colorTransform = ct;
       } else if (label == "restore"){
         var ct:ColorTransform = new ColorTransform();
         dog_1.transform.colorTransform = ct;
     }
    
    
    }

    In Listing 27.4, you simply need to create a new ColorTransform instance (ct) and pass it to the colorTransform property of the MovieClip instance, dog_1. A new ColorTransform instance has default multiplier and offset values. So, when it's passed to a MovieClip object, the color properties are set back to the original values.

  8. Save the Flash document again, and test the movie. Click the rabidButton instance you created in Step 3. After the dog_1 Movie Clip instance changes color, click the restoreButton instance you created in Step 6. Voila! The dog_1 Movie Clip instance reverts to its original color. Click the redButton instance that you created in the previous section. This button changes the appearance of the dog_1 Movie Clip instance to a solid red color. Now click the restoreButton instance—the dog_1 Movie Clip instance reverts to its original look!

Note

You can find the completed document, dogColor_200.fla, in the ch27 folder of this book's CD-ROM.

Although the ColorTransform.rgb property can alter basic color properties of MovieClip objects, the offset and multiplier properties are the color-control powerhouse. Any look that you can accomplish with the Advanced Effect dialog box, you can reproduce with the ColorTransform class.

Enabling Sound with ActionScript

ActionScript offers many classes, and one of the most exciting classes to use is the Sound class. As with most classes, the Sound class has predefined methods that you can use to control each new Sound class. Table 27.2 provides an overview of the Sound class and its common methods.

Tip

Flash Player 8 and higher can support up to 32 channels of audio (or 16 channels of stereo audio) simultaneously.

Table 27.2. Common Methods for the Sound Class

Method

Definition

Options

attachSound

Creates a new instance of a sound file (.aif or .wav) available in the Library. The new instance becomes a part of the Sound instance and can be targeted with Sound instance methods. Unlike attached Movie Clips, attached sounds do not require a depth number.

soundObject.attachSound(libraryID);

where:

soundObject refers to the Sound instance's name.

libraryID is the name of the sound in the Symbol Linkage properties (available in the Library).

loadSound

Loads a separate MP3 audio source file (.mp3) into a Sound object. You can begin playback of the MP3 sound as soon as enough bytes have downloaded, or wait until the entire file has downloaded. We will show you how to use this new method in Chapter 28.

soundObject.loadSound(URL, isStreaming);

where:

URL is the location of the MP3 file. This location can be a relative or absolute path.

isStreaming determines if the loading sound will begin playback as soon as enough bytes have downloaded (true), or if the entire sound must download before playback can begin (false).

start

Plays the targeted Sound instance. A sound must be attached to the Sound instance before it can play.

soundObject.start(inPoint, loopFactor);

where:

inPoint is the time (in seconds) in the sound where playback should begin.

loopFactor is the number of times the sound should be repeated.

Both of these parameters are optional and can be omitted.

stop

Stops playback of the targeted Sound instance. If no target is specified, all sounds are stopped. Note that this is not equivalent to pausing a sound. If a stopped sound is played later, it will start at the beginning (or at the inPoint).

soundObject.stop(libraryID);

where:

libraryID is the name of the sound in the Linkage properties (available in the Library).

setVolume

Changes the overall volume of the specified Sound instance. This method accepts values between 0 and 100 (in percentage units). You can enter percentages greater than 100 percent to increase sound output beyond its original recording level, but you may notice digital distortion of the sound.

soundObject.setVolume(volume);

where:

volume is a number between 0 and 100.

getVolume

Retrieves the current volume of the Sound instance.

soundObject.getVolume();

No options or arguments for this method.

setPan

Changes the offset of sound output from both the left and right channels.

soundObject.setPan(panValue);

where:

panValue is a value between −100 (full left-speaker output) and 100 (full right-speaker output). Use a value of 0 to balance sound output evenly.

getPan

Retrieves the values created with a previous setPan execution. You use this method to apply Pan settings consistently to multiple objects, or to store a Pan setting.

soundObject.getPan();

No options or arguments for this method.

setTransform

Changes the volume for each channel of the specified Sound object. This method also enables you to play the right channel in the left channel and vice versa.

soundObject.setTransform(soundTransformObject);

where:

soundTransformObject is the name of an object that has percentage properties for left and right output for the left channel, and left and right output for the right channel.

getTransform

Retrieves the values established with the last setTransform execution. You use this method to reapply sound transforms to new Sounds objects, or to store setTransform values.

soundObject.getTransform();

No options or arguments for this method.

The following list of Sound class features offers reasons for using Sound instances over traditional sound Movie Clips or keyframe sounds. You have:

  • Dynamic event sounds that play in a random or user-defined order

  • Precise control over volume and panning

  • The ability to dump (or erase) a Sound object when the sound is no longer needed

Note

All Sound objects are treated as Event sounds. You cannot use Sound objects to control the playback or frame rate like Stream sounds can. However, ActionScript does enable you to load MP3 files on the fly and "stream" their playback—these types of sounds, however, cannot control playback or frame-rate synchronization. For more information on Synch modes for sound, please refer to Chapter 15, "Adding Sound." (The usage of the term "stream" in this context does not imply real-time streaming, but rather a progressive download for the MP3 file.)

The Sound class uses sounds directly from the movie's library or from an MP3 file loaded at runtime. You cannot use the Sound class to control sounds specified in the Property inspector for any given keyframes.

Tip

You can, however, control Stream sounds attached to keyframes on a given timeline by controlling an empty Sound object. Any methods applied to the Sound object will be passed along to the Stream sound.

The next section shows you how to create Sound objects using the object constructor with the attachSound() and start() methods.

Creating sound libraries with ActionScript

In the Chapter 19, "Building Timelines and Interactions," you learned how to use behaviors to identify and play sounds. From a conceptual point of view, manually creating each sound behavior enabled you to see and work with each sound "object" very easily. However, you can produce the sounds for a sound library much more quickly using your own ActionScript code.

Note

In this section, you start with the linked sounds you created in Chapter 19, "Building Timelines and Interactions." Make a copy of the pianoKeys_sounds.fla file from the ch19 folder of this book's CD-ROM.

  1. Using the Open External Library command in the File

    Creating sound libraries with ActionScript
  2. If you don't have a new untitled Flash document open, create a new Flash file (ActionScript 2.0). Save the new document as soundLib_ActionScript.fla.

  3. Change the background color of the document to black in the Document Properties dialog box (Modify

    Creating sound libraries with ActionScript
  4. Open the new document's Library panel (Ctrl+L or

    Creating sound libraries with ActionScript
  5. Close the pianoKeys_sounds Library panel, and save your Flash document.

    The imported sounds with their linkage identifiers displayed

    Figure 27.6. The imported sounds with their linkage identifiers displayed

  6. Now, you need to add the ActionScript code that will create your Sound objects. You will construct a function that, when executed, will form a list of sound instances. On the Main Timeline (that is, Scene 1), rename Layer 1 to actions. Alt+double-click (or Option+double-click on the Mac) frame 1 of this layer. This opens the Actions panel. Type the following code into the Script pane:

    var sounds:Array;
    
    function createLib(num:Number):Void {
      var lib:MovieClip = this.createEmptyMovieClip("lib", 1);
      sounds = new Array();
      for (var i:Number = 1; i<=num; i++) {

    The first line establishes an array variable named sounds, which will store references to each new sound added to the sound library. The next line of code establishes the name of your function, createLib(). You will want to dynamically change the number of sounds you create with this function. Therefore, we assign an optional parameter (called an argument) num that will be passed to the nested actions within the function.

    The third line creates an empty MovieClip object, lib. This instance will hold individual sound targets, which you create in the next step.

    The fourth line creates a new Array object, sounds. This array stores the Sound objects that the createLib() function creates.

    The fifth line starts a for loop that cycles its nested actions until the condition i<=num is no longer true. i starts (or initializes) with a value of 1, and the syntax i++ tells i to increase by 1 with each pass of the for loop.

    In the next step, you want the for loop to create a new instance of the Sound object for each sound in the Library, and attach each sound in the Library to its new instance.

  7. In the Actions panel, add the following ActionScript to the code from Step 6:

    var mc:MovieClip = lib.createEmptyMovieClip("snd_"+i, i);
      var snd:Sound = new Sound(mc);
      snd.attachSound("key_"+i);
      sounds.push(snd);
     }
    }

    The first line creates a new MovieClip object, whose name starts with snd_. This instance is stored with the lib instance. The local variable mc is a reference to the new MovieClip object as well. With each pass of the loop, a new instance is created (for example, snd_1, snd_2, and so on). Each instance is used to store the attached sound later in the for loop.

    The second line makes a new Sound object that points to the timeline referenced by the target variable. Ultimately, your Sound objects will be tied to instances nested within the lib Movie Clip instance, which you'll see later.

    The third line uses the attachSound() method to take a sound element in the Library and attach it to the Sound object. The argument for the attachSound() method is specified as "key_" + i. On each pass of the for loop, this expression will return "key_1", "key_2", and so on until the limit prescribed by the num argument is reached.

    The complete block of code on the first keyframe of the actions layer is shown in Listing 27.5.

    Example 27.5. The createLib() Function

    var sounds:Array;
    
    function createLib(num:Number):Void {
       var lib:MovieClip = this.createEmptyMovieClip("lib", 1);
       sounds = new Array();
       for (var i:Number = 1; i <= num; i++) {
          var mc:MovieClip = lib.createEmptyMovieClip("snd_" + i, i);
          var snd:Sound = new Sound(mc);
          snd.attachSound("key_" + i);
          sounds.push(snd);
       }
    }
  8. Now that you have a function defined to create all the Sound objects, you need to invoke the function. With the code for frame 1 of the actions layer displayed in the Actions panel, type the following code just before the createLib() function definition:

    createLib(7);

    This line of code invokes the createLib() function. In addition to executing the createLib() method, you're also sending the function the number 7 as the num argument. Therefore, seven Sound objects are created.

  9. Save the Flash document and test it (Ctrl+Enter or

    The createLib() Function
    Variable _level0.sounds = [object #2, class 'Array'] [
        1:[object #3, class 'Sound'] {
          id3:[getter/setter] undefined,
          duration:[getter/setter] 1752,
          position:[getter/setter] 0
        },
        2:[object #4, class 'Sound'] {
          id3:[getter/setter] undefined,
          duration:[getter/setter] 1602,
          position:[getter/setter] 0
        },
        3:[object #5, class 'Sound'] {
          id3:[getter/setter] undefined,
          duration:[getter/setter] 1822,
          position:[getter/setter] 0
        },
        4:[object #6, class 'Sound'] {
          id3:[getter/setter] undefined,
          duration:[getter/setter] 1672,
          position:[getter/setter] 0
        },
        5:[object #7, class 'Sound'] {
          id3:[getter/setter] undefined,
          duration:[getter/setter] 1660,
          position:[getter/setter] 0
        },
        6:[object #8, class 'Sound'] {
          id3:[getter/setter] undefined,
          duration:[getter/setter] 1728,
          position:[getter/setter] 0
        },
        7:[object #9, class 'Sound'] {
          id3:[getter/setter] undefined,
          duration:[getter/setter] 1785,
          position:[getter/setter] 0
        }
      ]
  10. Close the Test Movie window and return to the Flash CS3 authoring environment. Select frame 1 of the actions layer and add this last bit of code to the Script pane:

    sounds[0].start();

    The first line of code targets the first declared element, 0, of the sounds object and tells it to begin playback with the start() method of the Sound class. Remember that element 0 in the array is a Sound object, which references the key_1 ID in the Library.

  11. Save the Flash document and test it. You will hear key_1 sound (key_1.wav or key_1.aif) play.

Now you should practice targeting these Sound objects from other event handlers, such as buttons and more keyframes. To access a different sound, simply change the number in the array brackets. In the next chapter, you'll learn how to load a Flash movie file (.swf) into another Flash movie, as well as how to load MP3 files directly into the movie.

Note

You can view the completed sound library movie, soundLib_ActionScript.fla, located in the ch27 folder of this book's CD-ROM. We've also included a bonus file, soundLib_onSoundComplete.fla, that demonstrates the onSoundComplete() handler of the Sound class. This handler detects when a sound has finished playing. In the bonus example, each sound plays successively, from key_1 all the way through key_7, and repeats.

Warning

You should attach only one sound per timeline (or Movie Clip instance). Although you can create more than one Sound object instance on a timeline, you cannot use the setVolume() method of the Sound class to control each individual sound—the volume will be set for all Sound object instances on the targeted timeline.

Creating a soundTransformObject

Two other methods of the Sound class, setTransform() and getTransform(), work with transform objects with specific properties to control volume distribution across channels. You need to create a generic object using the object constructor before the setTransform() method can be used with a Sound object. This generic object will become a soundTransformObject after you have assigned sound channel properties to the generic object.

Luckily, the soundTransformObject doesn't have as many properties as the ColorTransform class, and they're much simpler to predict with trial-and-error testing. The properties of the soundTransformObject are

  • ll—The percentage of left channel output in the left speaker

  • lr—The percentage of right channel output in the left speaker

  • rr—The percentage of right channel output in the right speaker

  • rl—The percentage of left channel output in the right speaker

The first letter of each property determines which physical speaker is being affected. The second letter determines which channel's output (or its volume) is played in that speaker. Each property can have a value between −100 and 100.

Tip

Use the soundTransformObject to vary the output of the sounds in the soundLib example you created in this section. As with the setTransform() example for the Color object, create buttons that create and execute unique transform settings.

Creating volume and balance sliders for sounds

In this section, you learn how to control the volume and balance output from a Sound object using the slider mechanism from Chapter 25, "Controlling Movie Clips." The slider mechanism works by taking the X position value of the slider's bar and applying it to a property of another object. In Chapter 25, you applied the position value of the bar to Movie Clip properties such as _xscale, _yscale, and _alpha. In this exercise, you apply the position values to the setVolume() and setPan() methods of the Sound object to control the volume and balance output, respectively.

Note

In this section, you need to use the slider_basic_104.fla file, located in the ch25 folder of this book's CD-ROM. If you want to learn how this slider was built, read Chapter 25, "Controlling Movie Clips."

The first part of this exercise shows you how to add the slider to a new document, import a sound, and control the volume of the sound with the slider. In the last steps, you apply the same methodology to the balance slider.

  1. Open your copy of the slider_basic_104.fla file via the File

    Creating volume and balance sliders for sounds
  2. Create a new Flash file (ActionScript 2.0). Save this document as soundSlider_100.fla.

  3. Rename Layer 1 to volumeSlider.

  4. Drag the sliderClip symbol from the slider_basic_104.fla Library panel to the new document's Stage. When you have finished, close the slider_basic_104.fla Library panel.

  5. With the slider instance selected on the Stage, open the Property inspector. Name the instance volumeSlider. In the Transform panel, rotate the instance −90 degrees. (You can also use the Free Transform tool to rotate the instance.)

  6. Now you need to create a Sound object. Import a sound file into the Flash document. Use a sound file that is at least 20 seconds long. You can import the atmospheres_1.wav (or .aif) file located in the resources folder of this book's CD-ROM.

  7. After you have imported a sound file, select the sound in the Library panel. Right-click (Control+click on Mac) the sound file and choose Linkage in the contextual menu. In the Linkage Properties dialog box, select the Export for ActionScript check box and type sound_1 in the Identifier field. Click OK to close the dialog box.

  8. Create a new layer on the Main Timeline (that is, Scene 1), and name the layer actions.

  9. Select frame 1 of the actions layer and open the Actions panel (F9, or Option+F9 on Mac). In the Script pane, type the following code:

    var sndBg:Sound = new Sound();
    sndBg.attachSound("sound_1");
    sndBg.start(0, 999);

    Note

    This code uses ActionScript 2.0's strict typing feature to declare the sndBg variable as a Sound data type. Notice that once you declare the data type of a variable, you'll see the code hints for the data type (in this case, the Sound class) appear after you type the variable's name, sndBg, followed by a period.

    This code creates the Sound object that the volumeSlider instance will control. Line 1 uses the new Sound() constructor to establish a Sound object name sndBg. Line 2 links the sound_1 asset (that is, the sound file in the Library) to the sndBg object. Line 3 plays the sound, starting at the beginning of the sound (0), and looping it 999 times for near-indefinite playback.

  10. Save your Flash document. Test the movie (Ctrl+Enter or

    Creating volume and balance sliders for sounds

    To change the volume of the sndBg object, you need to take the position of the bar in the slider and apply its value to the setVolume() method of the sndBg object. You'll use ActionScript's event handlers to accomplish this.

  11. Select frame 1 of the actions layer on the Main Timeline. Open the Actions panel, and insert the following code after the last action in the Script pane:

    var volumeSlider:MovieClip;
    volumeSlider.onMouseMove = function():Void {
     var vol:Number = this.pos._x/2;
     sndBg.setVolume(vol);
    };

    This code declares an onMouseMove() handler for the volumeSlider instance. Each time a mouse move is detected, the function defined for this handler executes. The first line of the function retrieves the current _x value of the mcPos instance inside of volumeSlider and divides it by 2. (See our coverage of the slider in Chapter 25, "Controlling Movie Clips" to learn more about this operation.) This value, declared as vol, is then applied to the setVolume() method of the sndBg object.

  12. Save your Flash document again, and test it. Click and drag the bar on the slider. As you move it up, the sound increases in volume. As you move it down, the volume decreases.

    Creating a slider that controls the balance output is almost identical to the process of creating the volumeSlider instance. You will make another instance of the sliderClip symbol, and add a new onMouseMove() handler for the new instance.

  13. Create a new layer on the Main Timeline, and name it balanceSlider.

  14. Drag an instance of the sliderClip symbol from the Library to the Stage. Place the instance to the right of the volumeSlider instance. In the Property inspector, name the instance balanceSlider.

  15. Select frame 1 of the actions layer, and open the Actions panel. After the last line of code in the Script pane, type the following code:

    var balanceSlider:MovieClip;
    balanceSlider.onMouseMove = function():Void {
     var pan:Number = this.pos._x - 100;
     sndBg.setPan(pan);
    };

    This code declares an onMouseMove() handler for the balanceSlider instance. When the mouse moves within the Flash movie, the function for the onMouseMove() handler executes. In this function, though, we need to translate the _x property of the mcPos instance differently. Because pan values are within a range of −100 to 100, we need to map the 0 to 200 range of the slider accordingly. In order for the lowest value (0) to equal −100 and the highest value (200) to equal 100, you simply subtract 100 from the current _x property value returned by the position instance. You then apply this value to the setPan() method of the sndBg object.

  16. Save your Flash document and test it. As you drag the bar on the mcBal instance to the right, you should hear the sound play in the right speaker. As you drag the bar to the left, you should hear the sound play in the left speaker.

Note

You can find the completed soundSlider_100.fla file in the ch27 folder of this book's CD-ROM.

Printing with ActionScript

Using the new PrintJob class introduced with Flash Player 7 ActionScript, you can enable your Flash movies to output Flash artwork, text, and bitmaps. With these actions, you can do the following:

  • Create Flash ads that have printable specifications for e-commerce merchandise. Imagine if the next car ad you saw on your favorite Web site automatically printed dealer locations and maps without having to go to the car manufacturer's Web site?

  • Make Flash coupons. You can design printable coupons for e-tailers on the Web that can be printed and redeemed at their brick-and-mortar stores.

  • Automate dynamic Web-generated invoices and receipts at e-commerce sites. With ActionScript, you can format ordered items and add dynamic data to printable sheets.

  • Print rich vector illustrations or photorealistic bitmaps from a Web site. You can design Flash portfolio sites that print samples of stock images, or create personalized vector artwork that can print unique images for each visitor.

  • E-mail printable Flash artwork to clients. The next time you have a proof of concepts or finished artwork that needs final approval, you can e-mail your clients the Flash artwork in a stand-alone projector or .swf file.

  • Design custom contact information pages. Are you sick of HTML tables that won't print your nice row-and-column–formatted pages of information consistently from browser to browser? Printable Flash frames print beautifully each time. You can even add a visitor's contact information to a dynamic database and print it.

Although we can't describe how to do all these tasks in the space of this chapter, we will show you how to get started with the last idea. The following exercise shows you how to use the new PrintJob class to build pages that can be sent to a user's printer. You'll also practice new ActionScript 2.0 coding conventions using strict data types.

Note

Because Flash natively uses vector artwork, it translates best when it is output to a PostScript printer. Nevertheless, the Flash Player produces high-quality output to both PostScript and non-PostScript printers.

Warning

The PrintJob class is only available for use in Flash Player 7-compatible movies. If you need to generate printable output for Flash Player 5 or 6, use the older print() and printAsBitmap() functions, as discussed in the Flash MX Bible by Robert Reinhardt and Snow Dowd (Wiley, 2002).

  1. Open the printjob_starter.fla file in the ch27 folder of this book's CD-ROM. This document has sample artwork in the library that you can use to practice printing exercises. Resave this document as printjob_noscale.fla.

  2. Rename Layer 1 to content.

  3. Create a new Movie Clip symbol (Insert

    Printing with ActionScript
  4. Select frame 1 of the page border layer. Using the Rectangle tool, draw a nonfilled rectangle with a black stroke. After you have drawn the rectangle, select the entire outline, and open the Property inspector. Choose a line style of Solid, at 1 px. In the width and height fields, enter values that are in the same aspect ratio as an 8.5″ × 11″ piece of paper. For example, as shown in Figure 27.10, the size 320 × 440 uses the same aspect ratio. Position the artwork's left corner at 0, 0.

  5. Add another layer in the contentClip timeline, and rename this layer content.

  6. Open the Library panel (Ctrl+L or

    Printing with ActionScript
  7. Save your Flash document.

  8. Go back to the Main Timeline (that is, Scene 1). On frame 1 of the content layer, drag an instance of the contentClip symbol from the Library panel to the Stage. In the Property inspector, name this instance content. Do not resize the instance. For now, just let the bottom edge of the instance run off the Stage.

  9. On the Main Timeline, create another layer named printButton. Place this layer above the content layer. The printButton layer will hold a Button component that the user can click to print the content instance.

    The frame artwork

    Figure 27.10. The frame artwork

    The siteLogo artwork

    Figure 27.11. The siteLogo artwork

  10. On frame 1 of the printButton layer, drag an instance of the Button component from the Components panel to the Stage. In the Property inspector, name this instance printButton. In the Parameters tab of the inspector, type Print into the label field. Refer to the settings shown in Figure 27.12.

    The printButton instance

    Figure 27.12. The printButton instance

  11. Create another layer, and name it actions. Place this layer above the other layers.

  12. Now, you're ready to add the ActionScript that will print the content instance. Select frame 1 of the actions layer, and open the Actions panel (F9, Option+F9 on Mac). In the Script pane, type the code shown in Listing 27.6.

    Line 1 declares the printButton instance as a Button component. By strong typing your variables (and instances) in ActionScript, the Actions panel displays the code hints for that variable (or instance) whenever you type the name and follow it with a period.

    On line 3, a printContent() function is added as an event listener for the printButton instance (line 16). Now, when the user clicks the Button component, the printContent() function will be invoked.

    Line 5 declares the printContent() function. Line 6 declares a local variable named pj, set to use the PrintJob data type, which invokes the constructor for the PrintJob class. Line 7 creates a local variable named mc, pointing to the mcContent instance.

    Line 8 uses the start() method of the PrintJob class to initiate a print session on the user's machine. When the start() method is invoked, the system's standard Print dialog box appears. If the user clicks OK in this dialog box, then lines 10 through 12 execute. If the user cancels the print request, lines 13 through 15 execute. If the user clicks OK, the local variable init is set to true. If the user cancels the dialog box, init is set to false.

    Line 9 checks the result of the user's input in the Print dialog box. If init is true, then lines 10 through 12 execute. In line 10, a trace() message is sent to the Output panel, indicating that a print job is being submitted. In line 11, the addPage() method of the PrintJob class is invoked, specifying the mcContent instance, represented by the variable mc, as the target instance to print. The addPage() method enables you to submit individual pages in a print job that is sent to the printer. When all of the addPage() methods are finished, you must initiate a send() method to complete the print job, as demonstrated in line 12.

    If the user cancels the Print dialog box, lines 13 through 15 execute. In line 14, a trace() message is sent to the Output panel, indicating that the print request was denied.

    Example 27.6. The printContent() Function

    1.  var printButton:mx.controls.Button;
    2.
    3.  printButton.addEventListener("click", printContent);
    4.
    5.  function printContent():Void {
    6.     var pj:PrintJob = new PrintJob();
    7.     var mc:MovieClip = content;
    8.     var init:Boolean = pj.start();
    9.     if (init) {
    10.       trace("printing...");
    11.       pj.addPage(mc);
    12.       pj.send();
    13.    } else {
    14.       trace("print aborted by user");
    15.    }
    16. }
  13. Save your Flash document, and test the movie. When you click the printButton instance, you should see the Print dialog box. If you click OK, the Output panel displays the "printing..." message. The first frame of the content instance will print at 100 percent on the outputted page. To accurately foretell what your printed dimensions will be in inches, divide the pixel width and height of your content clip by 72—there are 72 pixels to an inch. So, 320 × 440 will print at a size of 4.4″ × 6.1″. You can, however, scale the content clip to be printed, so that it will fill the entire page. In the next step, you'll learn how to do just that.

  14. Select frame 1 of the actions layer, and open the Actions panel. Add the bold code shown in Listing 27.7 to the printContent() function. Here, you use the pageWidth and pageHeight properties of the PrintJob object, pj, to calculate two variables, xscale and yscale. pageWidth and pageHeight return the size of the page output by the printer, in pixels. By dividing each value by the respective width and height of the content instance (mc) you can determine how much you need to scale the content instance to fill the entire page.

    Example 27.7. Scaling Content in the printContent() Function

    function printContent():Void {
       var pj:PrintJob = new PrintJob();
       var mc:MovieClip = content;
       var init:Boolean = pj.start();
       if (init) {
          trace("printing...");
          var pageWidth:Number = pj.pageWidth;
          var pageHeight:Number = pj.pageHeight;
          var xscale:Number = (pageWidth / mc._width) * 100;
          var yscale:Number = (pageHeight / mc._height) * 100;
          with (mc) {
             _xscale = xscale;
             _yscale = yscale;
          }
          pj.addPage(mc);
          pj.send();
       } else {
          trace("print aborted by user");
       }
    }
  15. Save your Flash document as printjob_scale.fla, and test it. When you click the printButton instance, the content instance scales to a larger size. The printed output will fill the entire page with the content instance's artwork.

  16. The last step will be to scale the content clip back to original size after the print output has been sent to the printer. Add the bold code shown in Listing 27.8 to the printContent() function.

    Example 27.8. Resetting the Scale of the clip Instance

    function printContent():Void {
       var pj:PrintJob = new PrintJob();
       var mc:MovieClip = mcContent;
       var bInit:Boolean = pj.start();
       if (bInit) {
          trace("printing...");
          var pageWidth:Number = pj.pageWidth;
          var pageHeight:Number = pj.pageHeight;
          var xscale_orig:Number = mc._xscale;
          var yscale_orig:Number = mc._yscale;
          var xscale:Number = (pageWidth / mc._width) * 100;
    var yscale:Number = (pageHeight / mc._height) * 100;
          with (mc) {
             _xscale = xscale;
             _yscale = yscale;
          }
          pj.addPage(mc);
          pj.send();
          with (mc) {
             _xscale = xscale_orig;
             _yscale = yscale_orig;
          }
       } else {
          trace("print aborted by user");
       }
    }
  17. Save your Flash document, and test it. When you click the printButton instance, the artwork no longer scales on the Stage, but the printed output will be scaled.

Note

You can find the completed documents, printjob_noscale.fla and printjob_scale.fla, in the ch27 folder of this book's CD-ROM.

Note

You can find additional PrintJob tutorials written by Robert Reinhardt at Community MX. You can find a list of Robert's content at www.flashsupport.com/cmx.

We'd like to know what you think about this chapter. Visit www.flashsupport.com/feedback to send us your comments.

Summary

  • Collisions occur when two or more elements in a Flash movie touch each other. Whenever the space by one Movie Clip instance occupies the space of another, a collision, or "hit," has occurred.

  • You can detect simple user-initiated collisions by using the startDrag() method and _droptarget property of the MovieClip object.

  • Using the hitTest() method of the MovieClip object, you can detect the intersection of X and Y coordinates with a specified Movie Clip instance. You can also use hitTest in a similar fashion to _droptarget, where the overlap of two specific Movie Clip instances is detected.

  • You can use the ColorTransform class to create new color values and apply them to Movie Clip instances.

  • You can create sound libraries in less time by using ActionScript and the Sound object. You create Sound objects by using Linkage identifiers for sound files in the movie's Library.

  • By using the new PrintJob class, you can output high-quality artwork to a PostScript or non-PostScript printer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.135.224