What is Software? | What is Education? | What is Technology? | What is Research? | What is Wi-Fi? | What is Communication? | What is Customer Service?

Free SEO Tutorials & Help

Tutorials:   Adobe Flash   Adobe Photoshop   CorelDRAW   SEO  

Site Map

Website Development | Cable & Broadband Magazine | Solutions for Higher Education | Auction Anything Online

Adobe Flash Help & Tutorials

 Back to Topics

 

Learning Animation, Filters and Drawings in Flash

Scripting animation with ActionScript 2.0

About animation and frame rate

Fading objects with code

Adding color and brightness effects with code

Moving objects with code

Panning an image with code

About bitmap caching, scrolling, and performance

About the Tween and TransitionManager classes

Adding tweens and transitions to a file in Flash Professional 8
(Flash Professional 8 only)

Animating with the TransitionManager and Tween classes

About easing classes and methods

About the Tween class

Using the Tween class

About continuing animations using the continueTo() method

Creating animations that run continuously

Combining the TransitionManager and Tween classes

Using filter effects

Working with filter packages

Working with filters, caching, and the MovieClip class

About hit detection, rotating, skewing, and scaling filters

Applying filters to object instances and BitmapData instances

About error handling, performance, and filters

Working with filters using ActionScript

Using the blur filter

Using the drop shadow filter

Using the glow filter

Creating gradient glows

Using the bevel filter

About the gradient bevel filter

Applying a gradient bevel filter

Using the color matrix filter

Using the convolution filter

Using the displacement map filter

Manipulating filter effects with code

Adjusting filter properties

Animating a filter by using ActionScript

Using the clone() method

Creating bitmaps with the BitmapData class

About blending modes

Applying blending modes

About operation order

Drawing with ActionScript

Using drawing methods to draw lines, curves, and shapes

Drawing specific shapes

Using complex gradient fills

Using line styles

Setting stroke and caps styles

Setting parameters of line styles

Using Drawing API methods and scripting animation

Understanding scaling and slice guides

Working with 9-slice scaling in ActionScript

 

Scripting animation with ActionScript 2.0

TOP

You can use ActionScript 2.0 to add animation to your Flash applications, instead of using motion or shape tweens on a timeline.The following sections show you how to use code to animate instances, such as changing the transparency and appearance of the instance, and moving the instance around the Stage.

For information on using the Tween and TransitionManager classes to further automate code-based animations. These classes help you add advanced easing equations and transition animations to movie clip instances in your application. Many of these effects are difficult to recreate using ActionScript without these prebuilt classes, because the code you need to use involves writing complex mathematical equations to achieve the effect.

The following sections describe how to script animations:

  • About animation and frame rate

  • Fading objects with code

  • Adding color and brightness effects with code

  • Moving objects with code

  • Panning an image with code

About animation and frame rate

TOP

When you add animation to an application, consider the frame rate that you set your FLA file to. You need to think about frame rate when working with animations because it can affect the performance of your SWF file and the computer that plays it. Setting a frame rate too high can lead to processor problems, especially when you use many assets or use ActionScript to create animation.

However, you also need to consider the frame rate setting, because it affects how smoothly your animation plays. For example, an animation set to 12 frames per second (fps) in the Property inspector plays 12 frames each second. If the document's frame rate is set to 24 fps, the animation appears to animate more smoothly than if it ran at 12 fps. However, your animation at 24 fps also plays much faster than it does at 12 fps, so the total duration (in seconds) is shorter. Therefore, if you need to make a 5-second animation using a higher frame rate, it means you need to add additional frames to fill those five seconds than at a lower frame rate (and thus, this raises the total file size of your animation). A 5-second animation at 24 fps typically has a higher file size than a 5-second animation at 12 fps.

NOTE : When you use an onEnterFrame event handler to create scripted animations, the animation runs at the document's frame rate, similar to if you created a motion tween on a timeline. An alternative to the onEnterFrame event handler is setInterval (see setInterval function in the ActionScript 2.0 Language Reference). Instead of depending on frame rate, you call functions at a specified interval. Like onEnterFrame, the more frequently you use setInterval to call a function, the more resource intensive the animation is on your processor.

Use the lowest possible frame rate that makes your animation appear to play smoothly at runtime, which helps reduce the strain on the end-user's processor. Try not to use a frame rate that's more than 30 to 40 fps; high frame rates put a lot of stress on processors, and do not change the appearance of the animation much or at all at runtime.

Also, especially if you're working with timeline-based animation, select a frame rate for your animation as early as possible in the development process. When you test the SWF file, check the duration, and the SWF file size, of your animation. The frame rate greatly affects the speed of the animation.

 

Fading objects with code

TOP

When you work with movie clips on the Stage, you might want to fade the movie clip in or out instead of toggling its _visible property. The following procedure demonstrates how to use an onEnterFrame event handler to animate a movie clip.

To fade a movie clip by using code:

  1. Create a new Flash document called fade1.fla.

  2. Draw some graphics on the Stage using the drawing tools, or import an image to the Stage (File > Import > Import to Stage).

  3. Select the content on the Stage and select Modify > Convert to Symbol.

  4. Select the Movie clip option and click OK to create the symbol.

  5. Select the movie clip instance on the Stage and type img1_mc in the Instance Name text box in the Property inspector.

  6. Select Frame 1 of the Timeline, and add the following code to the Actions panel:

    img1_mc.onEnterFrame = function() {

    img1_mc._alpha -= 5;

    if (img1_mc._alpha <= 0) {

    img1_mc._visible = false;

    delete img1_mc.onEnterFrame;

    }

    };

    This code uses an onEnterFrame event handler, which is invoked repeatedly at the frame rate of the SWF file. The number of times per second that the event handler is called depends on the frame rate at which the Flash document is set. If the frame rate is 12 frames per second (fps), the onEnterFrame event handler is invoked 12 times per second. Likewise, if the Flash document's frame rate is 30 fps, the event handler is invoked 30 times per second.

  7. Select Control > Test Movie to test the document.

    The movie clip you added to the Stage slowly fades out.

You can modify the _alpha property by using the setInterval() function instead of an onEnterFrame event handler, as the next procedure shows.

To fade an object by using the setInterval() function:

  1. Create a new Flash document called fade2.fla.

  2. Draw some graphics on the Stage, or import an image to the Stage (File > Import > Import to Stage).

  3. Select the content on the Stage and select Modify > Convert to Symbol.

  4. Select the Movie clip option and click OK to create the symbol.

  5. Select the movie clip instance on the Stage and type img1_mc in the Instance Name text box in the Property inspector.

  6. Select Frame 1 of the Timeline and add the following code to the Actions panel:

    var alpha_interval:Number = setInterval(fadeImage, 50, img1_mc);

    function fadeImage(target_mc:MovieClip):Void {

    target_mc._alpha -= 5;

    if (target_mc._alpha <= 0) {

    target_mc._visible = false;

    clearInterval(alpha_interval);

    }

    }

    The setInterval() function behaves slightly differently than the onEnterFrame event handler, because the setInterval() function tells Flash precisely how frequently the code should call a particular function. In this code example, the user-defined fadeImage() function is called every 50 milliseconds (20 times per second). The fadeImage() function decrements the value of the current movie clip's _alpha property. When the _alpha value is equal to or less than 0, the interval is cleared, which causes the fadeImage() function to stop executing.

  7. Select Control > Test Movie to test the document.

    The movie clip you added to the Stage slowly fades out.

Adding color and brightness effects with code

TOP

In addition to using ActionScript to set and animate alpha fades. you can animate various color and brightness effects by using code instead of using the Filters panel in the Property inspector.

The following procedure loads a JPEG image and applies a color transform filter, which modifies the red and green channels as the mouse pointer moves along the x-axis and y-axis.

To change an object's color channels by using ActionScript:

  1. Create a new Flash document called colorTrans.fla.

  2. Select Frame 1 of the Timeline, and add the following code to the Actions panel:

    import flash.geom.Transform;

    import flash.geom.ColorTransform;

    var imageClip:MovieClip = this.createEmptyMovieClip("imageClip", 1);

    var clipLoader:MovieClipLoader = new MovieClipLoader();

    clipLoader.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", imageClip);

    var mouseListener:Object = new Object();

    mouseListener.onMouseMove = function():Void {

    var transformer:Transform = new Transform(imageClip);

    var colorTransformer:ColorTransform = transformer.colorTransform;

    colorTransformer.redMultiplier = (_xmouse / Stage.width) * 1;

    colorTransformer.greenMultiplier = (_ymouse / Stage.height) * 1;

    transformer.colorTransform = colorTransformer;

    }

    Mouse.addListener(mouseListener);

  3. Select Control > Test Movie to test the document, and then move the mouse pointer around the Stage.

    The image file that loads transforms colors as you move the mouse.

You can also use the ColorMatrixFilter class to convert a color image to a black and white image, as the following procedure shows.

To use the ColorMatrixFilter class to change an image to a grayscale image:

  1. Create a new Flash document called grayscale.fla.

  2. Select Frame 1 of the Timeline, and add the following code to the Actions panel:

    import flash.filters.ColorMatrixFilter;

    System.security.allowDomain

    var mcl_obj:Object = new Object();

    mcl_obj.onLoadInit = function(target_mc:MovieClip):Void {

    var myElements_array:Array = [0.3, 0.59, 0.11, 0, 0,

    0.3, 0.59, 0.11, 0, 0,

    0.3, 0.59, 0.11, 0, 0,

    0, 0, 0, 1, 0];

    var myColorMatrix_filter:ColorMatrixFilter = new ColorMatrixFilter(myElements_array);

    target_mc.filters = [myColorMatrix_filter];

    }

    this.createEmptyMovieClip("img_mc", this.getNextHighestDepth());

    var img_mcl:MovieClipLoader = new MovieClipLoader();

    img_mcl.addListener(mcl_obj);

    img_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img_mc);

    The preceding code begins by importing the ColorMatrixFilter class, and creates a listener object that will be used with a new MovieClipLoader instance created in some later code. Next, a new movie clip instance is created with the instance name img_mc, as well as a new movie clip loader instance with the instance name img_mcl. Finally, the source movie clip is loaded into the img_mc movie clip on the Stage. When the image is successfully loaded, the onLoadInit event handler is called and attaches a ColorMatrixFilter to the loaded image.

  3. Select Control > Test Movie to test the document.

The image that you load onto the Stage changes to a grayscale image. View the image online (http://www.helpexamples.com/flash/images/image1.jpg) to see the original color of the image.

You can also set an image's brightness by using the ActionScript code in the following procedure.

To change an image's brightness:

  1. Create a new Flash document called brightness.fla.

  2. Select Frame 1 of the Timeline and add the following code to the Actions panel:

    import flash.filters.ColorMatrixFilter;

    System.security.allowDomain

    var mcl_obj:Object = new Object();

    mcl_obj.onLoadInit = function(target_mc:MovieClip):Void {

    var myElements_array:Array = [1, 0, 0, 0, 100,

    0, 1, 0, 0, 100,

    0, 0, 1, 0, 100,

    0, 0, 0, 1, 0];

    var myColorMatrix_filter:ColorMatrixFilter = new ColorMatrixFilter(myElements_array);

    target_mc.filters = [myColorMatrix_filter];

    }

    this.createEmptyMovieClip("img_mc", this.getNextHighestDepth());

    var img_mcl:MovieClipLoader = new MovieClipLoader();

    img_mcl.addListener(mcl_obj);

    img_mcl.loadClip("http://www.helpexamples.com/flash/images/image2.jpg", img_mc);

    This block of code uses the MovieClipLoader class to load an external JPEG. When the image successfully loads, the MovieClipLoader class onLoadInit event handler is called and modifies the image brightness to 100 using the ColorMatrixFilter filter.

  3. Select Control > Test Movie to test the document.

The image that you load into the SWF file changes its brightness when you test the SWF file. View the image online (http://www.helpexamples.com/flash/images/image2.jpg) to see the original appearance of the image.

 

Moving objects with code

TOP

Using ActionScript to move an object is similar to modifying an object's _alpha property, except that you instead modify the object's _x or _y property.

The following procedure animates a dynamically loaded JPEG image and slides it horizontally across the Stage.

To move an instance on the Stage by using code:

  1. Create a new Flash document called moveClip.fla.

  2. Change the frame rate of the document to 24 fps in the Property inspector.

    The animation is much smoother if you use a higher frame rate, such as 24 fps

  3. Select Frame 1 of the Timeline, and add the following code to the Actions panel:

    // Create a movie clip instance.

    this.createEmptyMovieClip("img1_mc", 10);

    var mcl_obj:Object = new Object();

    mcl_obj.onLoadInit = function (target_mc:MovieClip):Void {

    target_mc._x = Stage.width;

    target_mc.onEnterFrame = function() {

    target_mc._x -= 3; // decrease current _x position by 3 pixels

    if (target_mc._x <= 0) {

    target_mc._x = 0;

    delete target_mc.onEnterFrame;

    }

    };

    };

    var img_mcl:MovieClipLoader = new MovieClipLoader();

    img_mcl.addListener(mcl_obj);

    // Load an image into the movie clip

    img_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img1_mc);

    This code example loads an external image from a remote web server and, when the image is fully loaded, animates it horizontally across the Stage. Instead of using an onEnterFrame event handler, you could use the setInterval() function to animate the image.

  4. Select Control > Test Movie to test the document.

The image loads and then animates from the right side of the Stage to the upper-left corner of the Stage.

 

Panning an image with code

TOP

Using ActionScript, you can easily pan large images within your Flash documents. This is useful when your image doesn't fit on the Stage, or you want to create an animation effect in which you pan a movie clip from one side of the Stage to the other. For example, if you have a large panoramic image that is larger than your Stage size, but you don't want to reduce the dimensions of your image or increase the dimensions of your Stage, you can create a movie clip that acts as a mask for the larger image.

The following procedure demonstrates how you can dynamically mask a movie clip and use an onEnterFrame event handler to animate an image behind the mask.

To pan an instance on the Stage using code:

  1. Create a new Flash document called pan.fla.

  2. Change the frame rate of the document to 24 fps in the Property inspector.

    The animation is much smoother if you use a higher frame rate, such as 24 fps.

  3. Select Frame 1 of the Timeline, and add the following code to the Actions panel:

    System.security.allowDomain

    // initialize variables

    var direction:Number = -1;

    var speed:Number = 5;

    // create clip to load an image into

    this.createEmptyMovieClip("img_mc", 10);

    // create a clip to use as a mask

    this.createEmptyMovieClip("mask_mc", 20);

    // use the Drawing API to draw/create a mask

    with (mask_mc) {

    beginFill(0xFF0000, 0);

    moveTo(0, 0);

    lineTo(300, 0);

    lineTo(300, 100);

    lineTo(0, 100);

    lineTo(0, 0);

    endFill();

    }

    var mcl_obj:Object = new Object();

    mcl_obj.onLoadInit = function(target_mc:MovieClip) {

    // set the target movie clip's mask to mask_mc

    target_mc.setMask(mask_mc);

    target_mc.onEnterFrame = function() {

    target_mc._x += speed * direction;

    // if the target_mc is at an edge, reverse the animation direction

    if ((target_mc._x <= -(target_mc._width-mask_mc._width)) || (target_mc._x >= 0)) {

    direction *= -1;

    }

    };

    };

    var my_mcl:MovieClipLoader = new MovieClipLoader();

    my_mcl.addListener(mcl_obj);

    my_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img_mc);

    The first section of code in this code example defines two variables: direction and speed. The direction variable controls whether the masked image scrolls from left to right (1) or right to left (-1). The speed variable controls how many pixels are moved each time the onEnterFrame event handler is called. Larger numbers cause the animation to move more quickly, although the animation appears a bit less smooth.

    The next section of code creates two empty movie clips: img_mc and mask_mc. A 300 pixel by 100 pixel rectangle is drawn inside the mark_mc movie clip using the Drawing API. Next, a new object (mcl_obj) is created, which you use as a listener for a MovieClipLoader instance created in the final block of code. This object defines an event listener for the onLoadInit event, masks the dynamically loaded image, and sets up the scrolling animation. After the image reaches the left or right edge of the mask, the animation reverses.

    The final block of code defines a MovieClipLoader instance, specifies the listener object you created earlier, and begins loading the JPEG image into the img_mc movie clip.

  4. Select Control > Test Movie to test the document.

The image loads and then animates back and forth in a panning motion (side to side motion). The image is masked at runtime. To see the original image, you can view it online (http://www.helpexamples.com/flash/images/image1.jpg).
 

About bitmap caching, scrolling, and performance

TOP

Flash Player 8 introduces bitmap caching, which helps you enhance the performance of nonchanging movie clips in your applications. When you set the MovieClip.cacheAsBitmap or Button.cacheAsBitmap property to true, Flash Player caches an internal bitmap representation of the movie clip or button instance. This can improve performance for movie clips that contain complex vector content. All of the vector data for a movie clip that has a cached bitmap is drawn to the bitmap, instead of to the main Stage.

NOTE :The bitmap is copied to the main Stage as unstretched, unrotated pixels snapped to the nearest pixel boundaries. Pixels are mapped one-to-one with the parent object. If the bounds of the bitmap change, the bitmap is re-created instead of being stretched.

  • Working with Movie Clips:

  • About caching and scrolling movie clips with ActionScript

  • Caching a movie clip

  • Setting the background of a movie clip

It's ideal to use the cacheAsBitmap property with movie clips that have mostly static content and that do not scale and rotate frequently. With such movie clips, using the cacheAsBitmap property can lead to performance improvements when the movie clip is translated (when its x and y position is changed). For detailed information about when to use this feature,

 

About the Tween and TransitionManager classes

TOP

When you install Flash Basic 8 or Flash Professional 8, you also install two powerful classes: the Tween and TransitionManager classes. This section describes how to use these classes with movie clips and Macromedia V2 components (included with Flash MX 2004 and Flash 8) to add animation easily to your SWF files.

If you create a slide presentation or form application with Flash Professional 8 (ActionScript 2.0 only), you can select behaviors that add different kinds of transitions between slides, which is similar to when you create a PowerPoint presentation. You add this functionality into a screen application by using the Tween and TransitionManager classes, which generate ActionScript that animates the screens depending on the behavior that you choose.

You can also use the Tween and TransitionManager classes outside of a screen-based document, in either Flash Basic 8 or Flash Professional 8. For example, you can use the classes with the component set of version 2 of the Macromedia Component Architecture, or with movie clips. If you want to change the way a ComboBox component animates, you can use the Transition Manager class to add some easing when the menu opens. Easing refers to gradual acceleration or deceleration during an animation, which helps your animations appear more realistic. You can also use the Tween and TransitionManager classes, instead of creating motion tweens on the timeline or writing custom code, to create your own animated menu system.

NOTE : The Tween and TransitionManager classes are available only in ActionScript 2.0, but these classes are available in both Flash Basic 8 and Flash Professional 8.

 

Adding tweens and transitions to a file in Flash Professional 8
(Flash Professional 8 only)

TOP

 
Note : This section describes adding tweens and transitions to a Flash Professional slide presentation to demonstrate what they look like for Flash Professional users. However, you can add transitions and tweens to your Flash Basic 8 (or Flash Professional 8) applications if you use code. The following sections include examples that show you how.

The Tween and TransitionManager classes are designed to let you use simple ActionScript to add animations to parts of your SWF file. The Flash authoring environment contains behaviors that let you use these prebuilt classes for transitions in a screen-based application. To create a slide presentation or form application, you can select behaviors that add different kinds of transitions between slides.

Before you start to use these transitions with movie clips in Flash, you should see what they do when you use a screen-based application.

To view the ActionScript that creates a transition in a slide presentation:

  1. Select File > New to create a new slide presentation in Flash Professional 8.

  2. Select Flash Slide Presentation from the General tab and click OK.

  3. Select Window > Behaviors to open the Behaviors panel.

  4. Click Add Behavior (+).

  5. Select Screen > Transition from the pop-up menu to open the Transitions dialog box.

  6. Select the Zoom transition.

  7. Type 1 into the Duration text box.

  8. Select Bounce from the Easing pop-up menu.

  9. Click OK to apply the settings and close the dialog box.

This adds about 15 lines of ActionScript directly onto the slide. The following snippet shows the relevant transition code:

mx.transitions.TransitionManager.start(eventObj.target, {type:mx.transitions.Zoom, direction:0, duration:1, easing:mx.transitions.easing.Bounce.easeOut, param1:empty, param2:empty});

This code calls the TransitionManager class and then applies the Zoom transition with the specified mx.transitions.easing.Bounce.easeOut easing method. In this case, the transition applies to the selected slide. To apply this effect to a movie clip, you can modify the ActionScript to use in your Flash animations. Modifying the code to work with a movie clip symbol is easy: change the first parameter from eventObj.target to the desired movie clip's instance name.

Flash comes with ten transitions, which you can customize by using the easing methods and several optional parameters. Remember, easing refers to gradual acceleration or deceleration during an animation, which helps your animations appear more realistic. For example, a ball might gradually increase its speed near the beginning of an animation, but slow down before it arrives at a full stop at the end of the animation. There are many equations for this acceleration and deceleration, which change the easing animation accordingly.

The following table describes the transitions included in Flash Basic 8 (using code) and Flash Professional 8 (using code or behaviors):

Transition

Description

Iris

Reveals the screen or movie clip by using an animated mask of a shape that zooms in.

Wipe

Reveals the screen or movie clip by using an animated mask of a shape that moves horizontally.

Pixel Dissolve

Masks the screen or movie clip by using disappearing or appearing rectangles.

Blinds

Reveals the next screen or movie clip by using disappearing or appearing rectangles.

Fade

Fades the screen or movie clip in or out.

Fly

Slides in the screen or movie clip from a particular direction.

Zoom

Zooms the screen or movie clip in or out.

Squeeze

Scales the current screen or movie clip horizontally or vertically.

Rotate

Rotates the current screen or movie clip.

Photo

Has the screen or movie clip appear like a photographic flash.

Each transition has slightly different customizations that you can apply to the animation. The Transitions dialog box lets you preview a sample animation before you apply the effect to the slide or form.

TIP : To preview how each transition works with the different methods in the easing classes, you can double-click Transition.swf in boot drive\Program Files\Macromedia\Flash 8\language\First Run\Behaviors\ folder or Macintosh HD:Applications:Macromedia Flash 8:First Run:Behaviors: to open the SWF file in the stand-alone player.

 

Animating with the TransitionManager and Tween classes

TOP

You can use the TransitionManager and Tween classes in Flash Basic 8 and Flash Professional 8 to add animations to movie clips, components, and frames using ActionScript. If you don't use the TransitionManager or the Tween class, you have to write custom code to animate movie clips or modify their level of transparency (alpha) and coordinates (location). If you add easing to the animation, the ActionScript (and mathematics) can become complex quickly. However, if you want to change the easing on a particular animation and you use these prebuilt classes, you can select a different class instead of trying to figure out the new mathematical equations you need to create a smooth animation.

The following procedure animates a movie clip so that it uses the TransitionManager class to zoom in on the Stage.

To animate a movie clip using the TransitionManager class:

  1. Select File > New and select Flash Document.

  2. Click OK to create the new FLA file.

  3. Save the FLA file as zoom.fla.

  4. Select File > Import > Import to Stage, and select an image on your hard disk to import into the FLA file.

    The image is imported into your file as a bitmap image, so you need to convert the image manually into a movie clip symbol.

  5. Click Open to import the image.

  6. Select the imported image on the Stage and select Modify > Convert to Symbol

  7. Name the symbol img1, and make sure you set the behavior to Movie Clip.

    By default, the registration point of the symbol is in the upper-left corner of the symbol.

  8. Click OK to convert the bitmap image into a movie clip.

  9. With the image still selected, open the Property inspector (Window > Properties > Properties), and assign the movie clip the instance name img1_mc.

  10. Select Frame 1 of the main Timeline and add the following ActionScript to the Actions panel:

    mx.transitions.TransitionManager.start(img1_mc, {type:mx.transitions.Zoom, direction:0, duration:1, easing:mx.transitions.easing.Bounce.easeOut, param1:empty, param2:empty});

    NOTE : For information on working with packages,

  11. Select Control > Test Movie to test the animation.

The image grows and has a slight bouncing effect before it returns to its original size. If the animation moves too quickly, increase the animation's duration (in the previous code snippet) from one second to two or three seconds (for example, duration:3).

You might notice that the image is anchored in the upper-left corner and grows toward the lower-right corner. This is different from the preview you see in the Transitions dialog box.

Creating complex animations is easy using the Tween and TransitionManager classes and doesn't require you to create motion or shape tweens on the timeline. Most importantly, you don't need to write complex math to create easing methods. If you want images to zoom in from the center instead of anchoring on a corner, modify the symbol's registration point when you convert the image from a bitmap into a symbol.

To zoom images in from the center of the image:

  1. Complete the steps in the previous procedure.

  2. Open the zoom.fla file, and select File > Save As to save a new copy of the document.

    Save the file as zoom2.fla.

  3. Drag a copy of the bitmap symbol from the Library panel onto the Stage beside the current movie clip symbol.

  4. With the bitmap image still selected on the Stage, press F8 to convert the symbol into a movie clip.

    Name the symbol img2.

  5. In the Convert to Symbol dialog box, click the center of the 3 x 3 grid to set the registration point to the center of the bitmap and click OK.

  6. Select the new movie clip on the Stage and use the Property inspector to give it an instance name of img2_mc.

  7. Select Frame 1 of the main Timeline and add the following ActionScript to the existing code:

    mx.transitions.TransitionManager.start(img2_mc, {type:mx.transitions.Zoom, direction:mx.transitions.Transition.IN, duration:1, easing:mx.transitions.easing.Bounce.easeOut});

  8. Select Control > Test Movie to test the animation.

    The second movie clip grows from the center of the symbol instead of the corner.

NOTE : Some transitions are sensitive to where you locate the registration point. Changing the registration point can have a dramatic effect on how the animation looks in a SWF file. For example, if the registration point is in the upper-left corner (default) when you use the Zoom transition, the transition begins from that location.

 

About easing classes and methods

TOP

Adding tweens and transitions to a file in Flash Professional 8 (Flash Professional 8 only) describes how to use the Bounce easing class to add a bouncing effect to the movie clip. In addition to Bounce, Flash 8 offers five additional easing classes, which are described in the following table:

 

Transition

Description

Back

Extends the animation beyond the transition range at one or both ends once to resemble an overflow effect.

Bounce

Adds a bouncing effect within the transition range at one or both ends. The number of bounces relates to the duration--longer durations produce more bounces.

Elastic

Adds an elastic effect that falls outside the transition range at one or both ends. The amount of elasticity is unaffected by the duration.

Regular

Adds slower movement at one or both ends. This feature lets you add a speeding up effect, a slowing down effect, or both.

Strong

Adds slower movement at one or both ends. This effect is similar to Regular easing, but it's more pronounced.

None

Adds an equal movement from start to end without effects, slowing down, or speeding up. This transition is also called a linear transition.

 

These six easing classes each have three easing methods, which are described in the following table:

Method

Description

easeIn

Provides the easing effect at the beginning of the transition.

easeOut

Provides the easing effect at the end of the transition.

easeInOut

Provides the easing effect at the beginning and end of the transition.


To open these classes in Flash or your ActionScript editor, browse to Hard Disk\Program Files\Macromedia\Flash 8\language\First Run\Classes\mx\transitions\easing\ folder on Windows (assumes a default installation), or Macintosh HD:Applications:Macromedia Flash 8:First Run:Classes:mx:transitions:easing.

The procedure on zooming images under Animating with the TransitionManager and Tween classes used the mx.transitions.easing.Bounce.easeOut easing class and method. In the folder on your hard disk, the ActionScript refers to the easeOut() method within the Bounce.as class. This ActionScript file is in the easing folder.

TIP : To preview how each transition works with the different methods in the easing classes, you can double-click Transition.swf in boot drive\Program Files\Macromedia\Flash 8\language\First Run\Behaviors\ or Macintosh HD:Applications:Macromedia Flash 8:First Run:Behaviors: to open the SWF file in the stand-alone player.

 

About the Tween class

TOP

The Tween class lets you move, resize, and fade movie clips easily on the Stage. The constructor for the mx.transitions.Tween class has the following parameter names and types:

function Tween(obj, prop, func, begin, finish, duration, useSeconds) {

// code ...

}

obj The movie clip object that the Tween instance targets.

prop A string name of a property in obj to which the values are to be tweened.

func The easing method that calculates an easing effect for the tweened object's property values.

begin A number that indicates the starting value of prop (the target object property to be tweened).

finish A number that indicates the ending value of prop (the target object property to be tweened).

duration A number that indicates the length of time of the tween motion. If omitted, the duration is set to infinity by default.

useSeconds A Boolean value related to the value you specify in the duration parameter, which indicates to use seconds if true, or frames if false.

For example, imagine that you want to move a movie clip across the Stage. You can add keyframes to a timeline and insert a motion or shape tween between them, you can write some code in an onEnterFrame event handler, or you can use the setInterval() function to call a function at periodic intervals. If you use the Tween class, you have another option that lets you modify a movie clip's _x and _y properties. You can also add the previously described easing methods. To take advantage of the Tween class, you can use the following ActionScript:

new mx.transitions.Tween(ball_mc, "_x", mx.transitions.easing.Elastic.easeOut, 0, 300, 3, true);

This ActionScript snippet creates a new instance of the Tween class, which animates the ball_mc movie clip on the Stage along the x-axis (left to right). The movie clip animates from 0 pixels to 300 pixels in three seconds, and the ActionScript applies an elastic easing method. This means that the ball extends past 300 pixels on the x-axis before using a fluid motion effect to animating back.

 

Using the Tween class

TOP

If you use the Tween class in more than one place in your Flash document, you might opt to use an import statement. This lets you import the Tween class and easing methods rather than give the fully qualified class names each time you use them, as the following procedure shows.

To import and use the Tween class:

  1. Create a new document and call it easeTween.fla.

  2. Create a movie clip on the Stage.

  3. Select the movie clip instance and type ball_mc into the Instance Name text box in the Property inspector.

  4. Select Frame 1 of the Timeline and add the following code in the Actions panel:

    import mx.transitions.Tween;

    import mx.transitions.easing.*;

    new Tween(ball_mc, "_x", Elastic.easeOut, Stage.width, 0, 3, true);

    This code example uses two import statements. The first statement imports the mx.transitions.Tween class only, and the second import statement uses the wildcard (*) shortcut to import each of the six easing classes by using a single line of code. The second statement imports an entire package of classes.

    NOTE : For information on working with packages,

  5. Select Control > Test Movie to see the animation.

Flash documentation defines package as directories that contain one or more class files and that reside in a designated classpath directory. In this case, the package resides in the C:\Program Files\Macromedia\Flash 8\language\First Run\Classes\mx\transitions\easing folder (Windows), or HD:Applications:Macromedia Flash 8:First Run:Classes:mx:transitions:easing (Macintosh). You might agree that importing an entire package is much better than having to import the six classes separately. Instead of referring to the mx.transitions.Tween class, your ActionScript directly refers to the Tween class. Likewise, instead of using the fully qualified class name for the easing classes, mx.transitions.easing.Elastic.easeOut for example, you can type Elastic.easeOut in your ActionScript code. For more information,

Using similar code, you set the _alpha property to fade instances in and out, instead of the _x property, as the next procedure shows.

To fade instances using the Tween class:

  1. Create a new document, and call it fadeTween.fla.

  2. Create a movie clip on the Stage.

  3. Select the movie clip instance, and type ball_mc into the Instance Name text box in the Property inspector.

  4. Select Frame 1 of the Timeline and add the following code in the Actions panel:

    import mx.transitions.Tween;

    import mx.transitions.easing.*;

    new Tween(ball_mc, "_alpha", Strong.easeIn, 100, 0, 3, true);

    Instead of moving around the Stage, now ball_mc fades from 100% visible to completely transparent in three seconds. To make the symbol fade out more quickly, change the duration parameter from 3 to 1 or 2.

  5. Select Control > Test Movie to see the animation.

If you change the document's frame rate, the animation appears to play more smoothly. For information on animation and frame rate,

Instead of using seconds, you can fade the symbol over a few frames. To set the duration in frames instead of seconds in the Tween class, you change the final parameter, useSeconds, from true to false. When you set the parameter to true, you tell Flash that the specified duration is in seconds. If you set the parameter to false, the duration is the number of frames you want to use for the tween. The next procedure shows how to set a tween to frames instead of seconds.

To set a duration of frames instead of seconds:

  1. Create a new document, and call it framesTween.fla.

  2. Create a movie clip on the Stage.

  3. Select the movie clip instance, and type ball_mc into the Instance Name text box in the Property inspector.

  4. Select Frame 1 of the Timeline, and add the following code in the Actions panel:

    import mx.transitions.Tween;

    import mx.transitions.easing.*;

    new Tween(ball_mc, "_alpha", Strong.easeIn, 100, 0, 24, false);

    This code fades out the ball_mc instance using the Strong.easeIn easing method. Instead of fading the instance for three seconds, it fades the instance across 24 frames.

  5. Select Control > Test Movie to see the animation.

    Wait a moment, then the instance fades out across 24 frames.

  6. Return to the authoring environment and open the Property inspector.

  7. Change the document's frame rate to 24 fps.

If you increase the frame rate of your FLA file, you see the instance fade out sooner. For information on animation and frame rate,

Using frames instead of seconds offers more flexibility, but remember that the duration relates to the frame rate of the current Flash document. If your Flash document uses a frame rate of 12 frames per second (fps), the previous code snippet fades the instance over two seconds (24 frames/12 fps = 2 seconds). However, if your frame rate is 24 fps, the same code fades the instance over one second (24 frames/24 fps = 1 second). If you use frames to measure duration, you can significantly change the speed of your animation when you change the document's frame rate, without modifying your ActionScript.

The Tween class has several more useful features. For example, you can write an event handler that triggers when the animation completes, as the next procedure shows.

To trigger code when an animation is completed:

  1. Create a new document, and call it triggerTween.fla.

  2. Create a movie clip on the Stage.

  3. Select the movie clip instance and type ball_mc into the Instance Name text box in the Property inspector.

  4. Select Frame 1 of the Timeline and add the following code in the Actions panel:

    import mx.transitions.Tween;

    import mx.transitions.easing.*;

    var tween_handler:Object = new Tween(ball_mc, "_alpha", Strong.easeIn, 100, 0, 3, true);

    tween_handler.onMotionFinished = function() {

    trace("onMotionFinished triggered");

    };

    If you test this ActionScript in your FLA file, you see the message "onMotionFinished triggered" appear in the Output panel after ball_mc finishes fading on the Stage.

  5. Select Control > Test Movie to see the animation.

Wait for a moment, and then the instance fades out. When it finishes tweening, you see the message appear in the Output panel.

About continuing animations using the continueTo() method

TOP

Using the Tween class demonstrates how to use the Tween class in your applications. However, if you want to move the ball after the initial animation is complete, there are at least two ways you can do it. One solution is to reanimate the ball by using the onMotionFinished event handler. However, the Tween class offers a simpler solution, the continueTo() method. The continueTo() method instructs the tweened animation to continue from its current value to a new value, as the following ActionScript shows:

import mx.transitions.Tween;

import mx.transitions.easing.*;

var ball_tween:Object = new Tween(ball_mc, "_x", Regular.easeIn, 0, 300, 3, true);

ball_tween.onMotionFinished = function() {

ball_tween.continueTo(0, 3);

};

After the initial tween finishes, the ball_mc movie clip tweens back to its original position at 0 pixels. The following snippet (edited for brevity) shows the function prototype for the continueTo() method:

function continueTo(finish:Number, duration:Number):Void {

/* omitted to save space. */

}

Only two arguments pass to the continueTo() method, instead of the seven arguments for the Tween constructor method, as the following snippet shows:

function Tween (obj, prop, func, begin, finish, duration, useSeconds) {

/* omitted to save space. */

}

The five parameters that aren't required by the continueTo() method (obj, prop, func, begin, and useSeconds) use the arguments that you defined earlier in the call to the Tween class. When you call the continueTo() method, you assume that the obj, prop, func (easing type), and useSeconds arguments are the same as in the earlier call to the Tween class. The continueTo() method uses the finish value from the call to the Tween class, instead of specifying a value for the begin argument, as the following ActionScript shows:

import mx.transitions.Tween;

import mx.transitions.easing.*;

var ball_tween:Object = new Tween(ball_mc, "_x", Regular.easeIn, 0, 300, 3, true);

ball_tween.onMotionFinished = function() {

ball_tween.continueTo(0, 3);

};

This code moves the ball_mc instance along the x-axis from 0 pixels to 300 pixels in three seconds. After the animation finishes, the onMotionFinished event handler is triggered and calls the continueTo() method. The continueTo() method tells the target object (ball_mc) to proceed from its current position and animate for three seconds along the x-axis to 0 pixels and to use the same easing method. You use the values specified in the call to the Tween constructor method for any parameters that you don't define in the continueTo() method. If you don't specify a duration for the continueTo() method, it uses the duration you specify in the call to the Tween constructor.
 

Creating animations that run continuously

TOP

You can make an animation continue moving back and forth along the x-axis without stopping. The Tween class accommodates this kind of animation with the aptly named yoyo() method. The yoyo() method waits for the onMotionFinished event handler to execute, and then it reverses the begin and finish parameters. The animation begins again, as the following procedure demonstrates.

To create an animation that continues endlessly:

  1. Create a new Flash document called yoyo.fla.

  2. Open the Actions panel and enter the following ActionScript on Frame 1 of the Timeline:

    import mx.transitions.Tween;

    import mx.transitions.easing.*;

    this.createEmptyMovieClip("box_mc", this.getNextHighestDepth());

    with (box_mc) {

    beginFill(0xFF0000, 60);

    moveTo(0, 0);

    lineTo(20, 0);

    lineTo(20, Stage.height);

    lineTo(0, Stage.height);

    lineTo(0, 0);

    endFill();

    }

    The first section code begins by importing the Tween class, as well as each class in the easing package. The next section of code creates a new movie clip with an instance name of box_mc and draws a rectangle 20 pixels wide and the same height as the Stage.

  3. Add the following ActionScript after the code created in the previous step:

    var box_tween:Tween = new Tween(box_mc, "_x", Regular.easeInOut, 0, Stage.width, 3, true);

    box_tween.onMotionFinished = function() {

    box_tween.yoyo();

    };

    This code creates a new tween to animate the box_mc movie clip across the Stage along the x-axis over 3 seconds.

  4. Select Control > Test Movie to test the animation.

    The box animates from left to right and back. If the animation isn't smooth, you might want to increase the document's frame rate from 12 fps to 24 fps.

    As the box approaches the right edge of the Stage, it animates outside the boundaries of the Stage. While this might not seem significant, you might not want the rectangle to disappear from view off the side of the Stage and then reappear a second later and animate in the other direction.

    To make adjustments, animate the rectangle from 0 pixels to the width of the Stage minus the width of the box_mc movie clip.

  5. To stop the rectangle from disappearing, revise the corresponding lines of code from step 3 to match the following code:

    var box_tween:Tween = new Tween(box_mc, "_x", Regular.easeInOut, 0, (Stage.width - box_mc._width), 3, true);

  6. Test the animation again (Control > Test Movie).

Now, the box stops easing before it goes off the boundaries of the Stage.
 

Combining the TransitionManager and Tween classes

TOP

You can generate interesting effects when you combine the TransitionManager and Tween classes. You can use the TransitionManager class to move a movie clip along the x-axis while you adjust the same clip's _alpha property using the Tween class. Each class can use a different easing method, which means you have many animation possibilities for objects in your SWF files.

You can take advantage of the continueTo() and yoyo() methods in the Tween class or the onMotionFinished event handler to create a unique effect.

You combine the TransitionManager and Tween classes to animate a dynamically loaded movie clip and fade it in on the Stage after it fully loads from the remote server, as the following procedure shows.

To use the TransitionManager and Tween classes together:

  1. Create a new Flash document and save the file as combination.fla.

  2. Add the following ActionScript on Frame 1 of the Timeline:

    import mx.transitions.*;

    import mx.transitions.easing.*;

    var mcl_obj:Object = new Object();

    mcl_obj.onLoadInit = function(target_mc:MovieClip) {

    new Tween(target_mc, "_alpha", Strong.easeIn, 0, 100, 2, true);

    TransitionManager.start(target_mc, {type:Fly, direction:Transition.IN, duration:3, easing:Elastic.easeInOut, startPoint:6});

    };

    var my_mcl:MovieClipLoader = new MovieClipLoader();

    my_mcl.addListener(mcl_obj);

    my_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", this.createEmptyMovieClip("img_mc", this.getNextHighestDepth()));

    This code is separated into three main sections.

    The first section of code imports the classes within the transitions package as well as the transitions.easing package. You import the entire transitions package in this example so you do not need to enter the fully qualified class name for the Tween class, TransitionManager class, or the selected transition (in this case, Fly). This process can reduce the amount of code you type and save you from potential typographical errors.

    The second section of ActionScript creates a listener object for the MovieClipLoader class instance, which you create in the third section of code. When the target movie clip loads into the MovieClipLoader instance, the onLoadInit event triggers and executes the block of code, which calls both the Tween class and the TransitionManager class. This event handler fades in the target movie clip because you modify the _alpha property in the Tween class, and flies the target movie clip along the x-axis.

    The third section of ActionScript code creates a MovieClipLoader instance and applies the listener object that you created earlier (so the target movie clip loader instance can listen for the onLoadInit event). Then you load the target JPEG image into a movie clip that you create dynamically by calling the createEmptyMovieClip() method.

  3. Save your document and select Control > Test Movie to view the animation in the test environment.

    After the external JPEG image finishes downloading from the server, the image fades in gradually and animates from right to left across the Stage.

TransitionManager class, in the Components Language Reference.

 

Using filter effects

TOP

Filters are visual effects that you can apply to objects rendered at runtime by Flash Player, such as movie clip instances. The filters include drop shadow, blur, glow, bevel, gradient glow, and gradient bevel. You can also use an adjust color filter that lets you edit a movie clip's brightness, contrast, saturation, and hue. You can apply filters using the Flash user interface in Flash

Professional 8, or using ActionScript in Flash Basic 8 or Flash Professional 8.

You can apply each of these filter effects to movie clips, buttons, or text fields by using either the Filters tab in the Property inspector or by using ActionScript. If you use ActionScript to apply the filters to an instance, you can also use a displacement map filter (see Using the displacement map filter) or a convolution filter (see Using the convolution filter). These filters are applied to the vector definitions, so there is no overhead of storing a bitmap image within the SWF file. You can also write ActionScript that lets you modify an existing filter that you applied to a text field, movie clip, or button.

The following procedure demonstrates how you could use an onEnterFrame event handler to animate a glow filter effect on a movie clip.

To animate a filter effect applied to a movie clip instance:

  1. Create a new Flash document and save it as animFilter.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    this.createEmptyMovieClip("box_mc", 10);

    box_mc.lineStyle(20, 0x000000);

    box_mc.beginFill(0x000000);

    box_mc.moveTo(0, 0);

    box_mc.lineTo(160, 0);

    box_mc.lineTo(160, 120);

    box_mc.lineTo(0, 120);

    box_mc.lineTo(0, 0);

    box_mc.endFill();

    box_mc._x = 100;

    box_mc._y = 100;

    box_mc.filters = [new flash.filters.GlowFilter()];

    var dir:Number = 1;

    box_mc.blur = 10;

    box_mc.onEnterFrame = function() {

    box_mc.blur += dir;

    if ((box_mc.blur >= 30) || (box_mc.blur <= 10)) {

    dir *= -1;

    }

    var filter_array:Array = box_mc.filters;

    filter_array[0].blurX = box_mc.blur;

    filter_array[0].blurY = box_mc.blur;

    box_mc.filters = filter_array;

    };

    This code completes two different functionalities. The first section creates and positions a movie clip instance, and draws a black rounded rectangle on the Stage. The second block of code applies a glow filter to the rectangle on the Stage and defines an onEnterFrame event handler, which is responsible for animating the filter effect. The onEnterFrame event handler animates the glow filter between a blur of 10 and 30 pixels, and after the animation is greater than or equal to 30, or less than or equal to 10, the direction of the animation reverses.

  3. Save your changes to the Flash document and select Control > Test Movie to test the SWF file.

     

Working with filter packages

TOP

Packages are directories that contain one or more class files and reside in a designated classpath directory. For example, the flash.filters package is a directory on your hard disk that contains several class files for each filter type (such as BevelFilter, BlurFilter, DropShadowFilter, and so on) in Flash 8. When class files are organized this way, you must access the classes in a specific way. You either import the class, or reference it using a fully qualified name.

NOTE : To use the import statement, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box.

The import statement lets you access classes without specifying their fully qualified names. For example, to use a BlurFilter in a script, you must refer to it by its fully qualified name (flash.filters.BlurFilter) or import it; if you import it, you can refer to it by its class name (BlurFilter) in your code instead. The following ActionScript code demonstrates the differences between using the import statement and using fully qualified class names.

If you don't import the BlurFilter class, your code needs to use the fully qualified class name (package name followed by class name) in order to use the filter:

// without importing

var myBlur:flash.filters.BlurFilter = new flash.filters.BlurFilter(10, 10, 3);

The same code, written with an import statement, lets you access the BlurFilter using the class name instead of continually referencing it using the fully qualified name. This can save typing and reduces the chance of making typing mistakes:

// with importing

import flash.filters.BlurFilter;

var myBlur:BlurFilter = new BlurFilter(10, 10, 3);

To import several classes within a package (such as the BlurFilter, DropShadowFilter, and GlowFilter) you can use one of two ways to import each class. The first way to import multiple classes is to import each class by using a separate import statement, as seen in the following snippet:

import flash.filters.BlurFilter;

import flash.filters.DropShadowFilter;

import flash.filters.GlowFilter;

If you use individual import statements for each class within a package, it becomes time consuming to write and prone to typing mistakes. You can avoid importing individual class files by using a wildcard import, which imports all classes within a certain level of a package. The following ActionScript shows an example of using a wildcard import:

import flash.filters.*; // imports each class within flash.filters package

The import statement applies only to the current script (frame or object) in which it's called. For example, suppose on Frame 1 of a Flash document you import all the classes in the macr.util package. On that frame, you can reference classes in the package by using their class names instead of their fully qualified name. To use the class name on another frame script, reference classes in that package by their fully qualified names or add an import statement to the other frame that imports the classes in that package.

When you use import statements, remember that classes are only imported for the level that you specify. For example, if you import all classes in the mx.transitions package, only the classes within the /transitions/ directory are imported, not all classes within subdirectories (such as the classes in the mx.transitions.easing package).

TIP : If you import a class but don't use it in your script, the class isn't exported as part of the SWF file. This means that you can import large packages without being concerned about the size of the SWF file; the bytecode associated with a class is included in a SWF file only if that class is actually used.

 

Working with filters, caching, and the MovieClip class

TOP

If a movie clip has an associated filter, it's marked to cache itself as a transparent bitmap when the SWF file loads. As long as the movie clip has at least one filter applied to it, Flash Player caches the movie clip as a bitmap at runtime by forcing the cacheAsBitmap property to be true. The cached bitmap is used as a source image for the filter effects. Each movie clip usually has two bitmaps: one bitmap is the original unfiltered source movie clip, the second bitmap is the final image after filtering. If you do not change the appearance of the movie clip at runtime, the final image does not need to update, which helps improve performance.

You can access filters applied to an instance by calling the MovieClip.filters property. Calling this property returns an array that contains each filter object currently associated with the movie clip instance. A filter itself has a set of properties unique to that filter, such as the following:

trace(my_mc.filters[0].angle); // 45.0

trace(my_mc.filters[0].distance); // 4

You can access and modify filters as you would a regular array object. Setting and getting the filters by using the property returns a duplicate of the filters object, not a reference.

To modify an existing filter, you can use code similar to the code in the following procedure.

To modify a filter's properties when applied to a movie clip instance:

  1. Create a new Flash document and save the file as modifyFilter.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    this.createEmptyMovieClip("my_mc", 10);

    // draw square

    with (my_mc) {

    beginFill(0xFF0000, 100);

    moveTo(0, 0);

    lineTo(100, 0);

    lineTo(100, 100);

    lineTo(0, 100);

    lineTo(0, 0);

    endFill();

    }

    my_mc._x = 100;

    my_mc._y = 100;

    // use default DropShadowFilter values

    my_mc.filters = [new flash.filters.DropShadowFilter()];

    trace(my_mc.filters[0].distance); // 4

    var filter_array:Array = my_mc.filters;

    filter_array[0].distance = 10;

    my_mc.filters = filter_array;

    trace(my_mc.filters[0].distance); // 10

    The first section of this code uses the Drawing API to create a red square, and positions the shape on the Stage. The second section of code applies a drop shadow filter to the square. Next, the code creates a temporary array to hold the current filters to apply to the red square on the Stage. The distance property of the first filter is set to 10 pixels, and the modified filter is reapplied to the my_mc movie clip instance.

  3. Select Control > Test Movie to test the document.

NOTE : Currently, no support is available for having any filters perform rotation based upon their parent's rotation or some sort of other rotation. The blur filter always blurs perfectly horizontally or vertically, independently of the rotation or skew of any item in the parent object tree.

TIP : Filtered content has the same restrictions on size as content with its cacheAsBitmap property set to true. If the author zooms in too far on the SWF file, the filters are no longer visible when the bitmap representation is greater than 2880 pixels in either direction. When you publish SWF files with filters, it is a good idea to disable the zoom menu options.

 

About hit detection, rotating, skewing, and scaling filters

TOP

No filtered region (drop shadow, for example) outside of a movie clip instance's bounding box rectangle is considered to be part of the surface for hit detection purposes (determining if an instance overlaps or intersects with another instance). Because hit detection is vector-based, you cannot perform a hit detection on the bitmap result. For example, if you apply a bevel filter to a button instance, hit detection is not available on the beveled portion of the instance.

Scaling, rotating, and skewing are not supported by filters; if the instance itself is scaled (_xscale and _yscale are not 100%), the filter effect does not scale with the instance. This means that the original shape of the instance rotates, scales, or skews; however, the filter does not rotate, scale, or skew with the instance.

You can animate an instance with a filter to create realistic effects, or nest instances and use the BitmapData class to animate filters to achieve this effect.
 

Applying filters to object instances and BitmapData instances

TOP

The use of filters depends on the object instance to which you apply the filter. Use the following guidelines when you apply a filter to an object or BitmapData instance:

  • To apply filters to movie clips, text fields, and buttons at runtime, use the filters property. Setting the filters property of an object does not modify the object and can be undone by clearing the filters property.

  • To apply filters to BitmapData instances, use the BitmapData.applyFilter() method. Calling applyFilter() on a BitmapData object modifies that BitmapData object and cannot be undone.

NOTE : (Flash Professional 8 only) You can also apply filter effects to images and video during authoring using the Filters tab in the Property inspector.

 

About error handling, performance, and filters

TOP

One problem that arises if you use too many filters in an application is the potential to use large amounts of memory and cause Flash Player performance to suffer. Because a movie clip with filters attached has two bitmaps that are both 32-bit, these bitmaps can cause your application to use a significant amount of memory if you use many bitmaps. You might see an out-of-memory error generated by the computer's operating system. On a modern computer, out-of-memory errors should be rare, unless you are using filter effects extensively in an application (for example, you have thousands of bitmaps on the Stage).

However, if you do encounter an out-of-memory error, the following occurs:

  • The filters array is ignored.

  • The movie clip is drawn using the regular vector renderer.

  • No bitmaps are cached for the movie clip.

After you see an out-of-memory error, a movie clip never attempts to use a filters array or a bitmap cache. Another factor that affects player performance is the value that you use for the quality parameter for each filter that you apply. Higher values require more CPU and memory for the effect to render, whereas setting the quality parameter to a lower value requires less computer resources. Therefore, you should avoid using an excessive number of filters, and use a lower quality setting when possible.

CAUTION : If a 100 pixel by 100 pixel object is zoomed in once, it uses four times the memory since the content's dimensions are now 200 pixels by 200 pixels. If you zoom another two times, the shape is drawn as an 800 pixel by 800 pixel object which uses 64 times the memory as the original 100 pixel by 100 pixel object. Whenever you use filters in a SWF file, it is always a good idea to disable the zoom menu options from the SWF file's context menu.

You can also encounter errors if you use invalid parameter types. Some filter parameters also have a particular valid range. If you set a value that's outside of the valid range, the value changes to a valid value that's within the range. For example, quality should be a value from 1 to 3 for a standard operation, and can only be set to 0 to 15. Anything higher than 15 is set to 15.

Also, some constructors have restrictions on the length of arrays required as input parameters. If a convolution filter or color matrix filter is created with an invalid array (not the right size), the constructor fails and the filter is not created successfully. If the filter object is then used as an entry on a movie clip's filters array, it is ignored.

TIP : When using a blur filter, using values for blurX and blurY that are powers of 2 (such as 2, 4, 8, 16, and 32) can be computed faster and give a 20% to 30% performance improvement.

 

Working with filters using ActionScript

TOP

The flash.filters package contains classes for the bitmap filter effects that are new in Flash Player 8. Filters let you use ActionScript to apply rich visual effects, such as blur, bevel, glow, and drop shadow, to text, movie clip, and button instances. You can also use the Flash authoring tool to apply filter effects to objects such as text, images, and video. Flash has nine filter effects, although only seven are accessible by using the user interface in Flash Professional 8. The ConvolutionFilter and DisplacementMapFilter filters are only available by using ActionScript code.

NOTE : All filters are availabe by using ActionScript in both Flash Basic 8 and Flash Professional 8.

The following procedure loads a semitransparent PNG image, and applies a GlowFilter effect to the nontransparent portion of the image.

To apply filters to semitransparent images:

  1. Create a new Flash document and save it as transparentImg.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import flash.filters.GlowFilter;

    System.security.allowDomain

    var mclListener:Object = new Object();

    mclListener.onLoadInit = function(target_mc:MovieClip) {

    target_mc._x = (Stage.width - target_mc._width) / 2;

    target_mc._y = (Stage.height - target_mc._height) / 2;

    var glow:GlowFilter = new GlowFilter();

    target_mc.filters = [glow];

    };

    this.createEmptyMovieClip("img_mc", 10);

    var img_mcl:MovieClipLoader = new MovieClipLoader();

    img_mcl.addListener(mclListener);

    img_mcl.loadClip("http://www.helpexamples.com/flash/images/logo.png", img_mc);

    This code uses a movie clip loader instance to load a semi-transparent PNG image. After the image finishes loading, the image moves to the center of the Stage and a glow filter is applied.

  3. Select Control > Test Movie to test the document.

Using the blur filter

TOP

The BlurFilter class lets you apply a blur visual effect to a variety of objects in Flash. A blur effect softens the details of an image. You can produce blurs that range from creating a softly unfocused look to a Gaussian blur, a hazy appearance like viewing an image through semi-opaque glass. The blur filter is based on a box-pass blur filter. The quality parameter defines how many times the blur should be repeated (three passes approximates a Gaussian blur filter).

NOTE : The blur filter scales only when you zoom into the Stage.

The following procedure blurs a dynamically loaded image based on the mouse pointer's current position on the Stage. The further the pointer is from the center of the Stage, the more the image is blurred.

To blur an image based on the mouse pointer's position:

  1. Create a new Flash document and save it as dynamicblur.fla.

  2. Add the following code to Frame 1 of the Timeline:

    import flash.filters.BlurFilter;

    System.security.allowDomain

    var mclListener:Object = new Object();

    mclListener.onLoadInit = function(target_mc:MovieClip) {

    // Center the target_mc movie clip on the Stage.

    target_mc._x = (Stage.width - target_mc._width) / 2;

    target_mc._y = (Stage.height - target_mc._height) / 2;

    };

    this.createEmptyMovieClip("img_mc", 10);

    var img_mcl:MovieClipLoader = new MovieClipLoader();

    img_mcl.addListener(mclListener);

    img_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img_mc);

    var blur:BlurFilter = new BlurFilter(10, 10, 2);

    var mouseListener:Object = new Object();

    mouseListener.onMouseMove = function():Void {

    /* Moving the pointer to the center of the Stage sets the blurX and blurY properties to 0%. */

    blur.blurX = Math.abs(_xmouse - (Stage.width / 2)) / Stage.width * 2 * 255;

    blur.blurY = Math.abs(_ymouse - (Stage.height / 2)) / Stage.height * 2 * 255;

    img_mc.filters = [blur];

    };

    Mouse.addListener(mouseListener);

    The first section of this code loads and positions a dynamically loaded image on the Stage. The second section defines a listener that is called whenever the mouse moves. You calculate the amount of horizontal and vertical blurring based on the mouse pointer's current position on the Stage. The further you move the pointer away from the center of the Stage, the more blurring is applied to the instance.

  3. Select Control > Test Movie to test the Flash document.

Move the mouse pointer along the x-axis to modify the amount of horizontal blurring. The instance blurs more when the pointer moves farther away from the horizontal center of the Stage. Moving the pointer along the y-axis causes the vertical blurring to increase or decrease, depending on the distance from the vertical center of the Stage.

TIP : When you use a blur filter, using values for blurX and blurY that are powers of two (such as 2, 4, 8, 16, and 32) can be computed faster and give a 20% to 30% performance improvement.

CAUTION : Setting a blur value lower than 1.03125 disables the blur effect.
 

Using the drop shadow filter 

TOP

The DropShadowFilter class lets you add a drop shadow to a variety of objects in Flash. The shadow algorithm is based on the same box filter that the blur filter uses . Several options are available for the style of the drop shadow, including inner or outer shadow and knockout mode.

The following procedure uses the Drawing API to draw a square on the Stage. When you move the mouse pointer horizontally along the Stage, this code modifies the distance from the square that the drop shadow appears, whereas moving the cusror vertically modifies how much the drop shadow blurs.

To use the drop shadow filter:

  1. Create a new Flash document and save it as dropshadow.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    // import the filter classes

    import flash.filters.DropShadowFilter;

    // create a movie clip called shapeClip

    this.createEmptyMovieClip("shapeClip", 1);

    // use the Drawing API to draw a shape

    with (shapeClip) {

    beginFill(0xFF0000, 100);

    moveTo(0, 0);

    lineTo(100, 0);

    lineTo(100, 100);

    lineTo(0, 100);

    lineTo(0, 0);

    endFill();

    }

    // position the shape

    shapeClip._x = 100;

    shapeClip._y = 100;

    // click the square, increase shadow strength

    shapeClip.onPress = function():Void {

    dropShadow.strength++;

    shapeClip.filters = [dropShadow];

    };

    // create a filter

    var dropShadow:DropShadowFilter = new DropShadowFilter(4, 45, 0x000000, 0.4, 10, 10, 2, 3);

    var mouseListener:Object = new Object();

    // create and apply a listener that controls the filter when the mouse moves

    mouseListener.onMouseMove = function():Void {

    dropShadow.distance = (_xmouse / Stage.width) * 50 - 20;

    dropShadow.blurX = (_ymouse / Stage.height) * 10;

    dropShadow.blurY = dropShadow.blurX;

    shapeClip.filters = [dropShadow];

    };

    Mouse.addListener(mouseListener);

    The first section of code creates a new movie clip and uses the Drawing API to draw a red square. The second section of code defines a mouse listener, which is called whenever the mouse moves. The mouse listener calculates the drop shadow's distance and level of blurring based on the current x and y positions of the mouse pointer, and reapplies the drop shadow filter. If you click the red square, the drop shadow's strength increases.

  3. Select Control > Test Movie to test the Flash document.

Move the mouse pointer along the x-axis to change the value of the drop shadow's distance, and move the mouse pointer along the y-axis to change the amount of blur applied to the movie clip instance.

 

You can also create drop shadows and apply them to dynamically loaded images. The following procedure demonstrates how you can load an external image and apply a drop shadow that follows the mouse pointer. The further the pointer moves away from the image's upper-left corner, the more horizontal and vertical blurring is applied to the image.

To create a drop shadow that follows the mouse pointer:

  1. Create a new Flash document and save it as dropshadowmouse.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import flash.filters.DropShadowFilter;

    System.security.allowDomain

    var dropShadow:DropShadowFilter = new DropShadowFilter(4, 45, 0x000000, 0.8, 10, 10, 2, 2);

    // Load and position the image on the Stage.

    var mclListener:Object = new Object();

    mclListener.onLoadInit = function(target_mc:MovieClip):Void {

    target_mc._x = (Stage.width - target_mc._width) / 2;

    target_mc._y = (Stage.height - target_mc._height) / 2;

    };

    this.createEmptyMovieClip("img_mc", 10);

    var img_mcl:MovieClipLoader = new MovieClipLoader();

    img_mcl.addListener(mclListener);

    img_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img_mc);

    // When mouse moves, recalculate the position of the drop shadow.

    var mouseListener:Object = new Object();

    mouseListener.onMouseMove = function():Void {

    var p1:Number = img_mc._y - _ymouse;

    var p2:Number = img_mc._x - _xmouse;

    var degrees:Number = Math.atan2(p1, p2) / (Math.PI / 180);

    dropShadow.distance = Math.sqrt(Math.pow(p1, 2) + Math.pow(p2, 2)) * 0.5;

    dropShadow.blurX = dropShadow.distance;

    dropShadow.blurY = dropShadow.blurX;

    dropShadow.angle = degrees - 180;

    img_mc.filters = [dropShadow];

    };

    Mouse.addListener(mouseListener);

    The first section of this code defines a drop shadow instance, loads an external image, and repositions the image at the center of the Stage. The second section of code defines a mouse listener, which you call whenever the user moves the mouse pointer around the Stage. Whenever the mouse moves, the event handler recalculates the distance and angle between the mouse pointer and the upper-left corner of the image. Based on this calculation, the drop shadow filter is reapplied to the movie clip.

  3. Select Control > Test Movie to test the Flash document.

When you run the SWF file, the drop shadow follows the mouse pointer. The closer you move the mouse pointer to the upper-left corner of the image on the Stage, the less of a blur effect is applied to the image. As the mouse pointer moves further from the upper-left corner of the image, the drop shadow effect becomes more apparent.

You can also apply drop shadows to dynamically loaded semitransparent PNG images. In the following procedure, the drop shadow filter is applied only to the solid area of the PNG, not the transparency.

To apply a drop shadow to a semitransparent image:

  1. Create a new Flash document and save it as dropshadowTransparent.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import flash.filters.DropShadowFilter;

    System.security.allowDomain

    var mclListener:Object = new Object();

    mclListener.onLoadInit = function(target_mc:MovieClip):Void {

    target_mc._x = (Stage.width - target_mc._width) / 2;

    target_mc._y = (Stage.height - target_mc._height) / 2;

    var dropShadow:DropShadowFilter = new DropShadowFilter(4, 45, 0x000000, 0.5, 10, 10, 2, 3);

    target_mc.filters = [dropShadow];

    };

    mclListener.onLoadError = function(target_mc:MovieClip):Void {

    trace("unable to load image.");

    };

    this.createEmptyMovieClip("logo_mc", 10);

    var my_mcl:MovieClipLoader = new MovieClipLoader();

    my_mcl.addListener(mclListener);

    my_mcl.loadClip("http://www.helpexamples.com/flash/images/logo.png", logo_mc);

    This ActionScript code uses the MovieClipLoader class to load an image and apply a drop shadow filter when the image is completely loaded from the remote server.

  3. Select Control > Test Movie to test the Flash document.

Flash loads a PNG image with a transparent background. When you apply the drop shadow filter, only the opaque (nontransparent) portion of the image has the filter applied.
 

Using the glow filter

TOP

The GlowFilter class lets you add a glow effect to various objects in Flash. The glow algorithm is based on the same box filter that is the blur filter uses. You can set the style of the glow in several ways, including inner or outer glow and knockout mode. The glow filter is similar to the drop shadow filter with the distance and angle properties of the drop shadow set to 0.

The following procedure demonstrates how you can apply a glow filter to a dynamically created movie clip on the Stage. Moving your mouse pointer around the Stage causes the movie clip's blur to change, and clicking the dynamically created shape causes the filter's strength to increase.

To use the glow filter:

  1. Create a new Flash document and save it as glowfilter.fla.

  2. Add the following ActionScript code to Frame 1 of the Timeline:

    import flash.filters.GlowFilter;

    this.createEmptyMovieClip("shapeClip", 10);

    with (shapeClip) {

    beginFill(0xFF0000, 100);

    moveTo(0, 0);

    lineTo(100, 0);

    lineTo(100, 100);

    lineTo(0, 100);

    lineTo(0, 0);

    endFill();

    }

    shapeClip._x = 100;

    shapeClip._y = 100;

    shapeClip.onPress = function():Void {

    glow.strength++;

    shapeClip.filters = [glow];

    };

    var glow:GlowFilter = new GlowFilter(0xCC0000, 0.5, 10, 10, 2, 3);

    var mouseListener:Object = new Object();

    mouseListener.onMouseMove = function():Void {

    glow.blurX = (_xmouse / Stage.width) * 255;

    glow.blurY = (_ymouse / Stage.width) * 255;

    shapeClip.filters = [glow];

    };

    Mouse.addListener(mouseListener);

    This code uses the Drawing API to draw a square on the Stage, and applies a glow filter to the shape. Whenever the mouse pointer moves along the x-axis or y-axis, the glow filter's blur is calculated and applied to the shape.

  3. Select Control > Test Movie to test the document.

The amount of horizontal and vertical blurring is calculated by the mouse pointer's current _xmouse and _ymouse position. As you move the mouse pointer to the upper-left corner of the Stage, the amount of horizontal and vertical blurring decreases. Conversely, as the mouse pointer moves to the lower-right corner of the Stage, the amount of horizontal and vertical blurring increases.

 

Creating gradient glows

TOP

The GradientGlowFilter class lets you create a gradient glow effect for a variety of objects in Flash. A gradient glow is a realistic-looking glow with a color gradient that you can specify. You can apply a gradient glow around the inner or outer edge of an object or on top of a object.

The following procedure uses the Drawing API to draw a square on the Stage, and then applies a gradient glow filter to the shape. Clicking the square on the Stage increases the filter's strength, whereas moving the mouse pointer horizontally or vertically modifies the amount of blurring along the x-axis or y-axis.

To apply a gradient glow filter:

  1. Create a new Flash document and save it as gradientglow.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import flash.filters.GradientGlowFilter;

    // create a new shapeClip instance

    var shapeClip:MovieClip = this.createEmptyMovieClip("shapeClip", 10);

    // use Drawing API to create a shape

    with (shapeClip) {

    beginFill(0xFF0000, 100);

    moveTo(0, 0);

    lineTo(100, 0);

    lineTo(100, 100);

    lineTo(0, 100);

    lineTo(0, 0);

    endFill();

    }

    // position the shape

    shapeClip._x = 100;

    shapeClip._y = 100;

    // define a gradient glow

    var gradientGlow:GradientGlowFilter = new GradientGlowFilter(0, 45, [0x000000, 0xFF0000], [0, 1], [0, 255], 10, 10, 2, 3, "outer");
     

    // define a mouse listener, listen for two events

    var mouseListener:Object = new Object();

    mouseListener.onMouseDown = function():Void {

    gradientGlow.strength++;

    shapeClip.filters = [gradientGlow];

    };

    mouseListener.onMouseMove = function():Void {

    gradientGlow.blurX = (_xmouse / Stage.width) * 255;

    gradientGlow.blurY = (_ymouse / Stage.height) * 255;

    shapeClip.filters = [gradientGlow];

    };

    Mouse.addListener(mouseListener);

    The previous code is split into three sections. The first section of code uses the Drawing API to create a square and positions the shape on the Stage. The second section of code defines a new gradient glow filter instance, which creates a glow from red to black. The third section of code defines a mouse listener, which listens for two mouse event handlers. The first event handler is onMouseDown, which causes the strength of the gradient glow to increase. The second event handler is onMouseMove, which is called whenever the mouse pointer moves within the SWF file. The further the mouse pointer moves from the upper-left corner of the Flash document, the stronger the glow effect that is applied.

  3. Select Control > Test Movie to test the document.

As you move your mouse pointer around the Stage, the gradient glow filter's blur increases and decreases strength. Click the left mouse button to increase the glow's strength.
 

Using the bevel filter

TOP

The BevelFilter class lets you add a bevel effect to a variety of objects in Flash. A bevel effect gives objects a three-dimensional look. You can customize the look of the bevel with different highlight and shadow colors, the amount of blur on the bevel, the angle of the bevel, the placement of the bevel, and a knockout effect.

The following procedure uses the Drawing API to create a square, and adds a bevel to the shape.

To use the bevel filter:

  1. Create a new Flash document and save it as bevel.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import flash.filters.BevelFilter;

    // define a bevel filter

    var bevel:BevelFilter = new BevelFilter(4, 45, 0xFFFFFF, 1, 0xCC0000, 1, 10, 10, 2, 3);

    // create a new shapeClip instance

    var shapeClip:MovieClip = this.createEmptyMovieClip("shapeClip", 1);

    // use the Drawing API to create a shape

    with (shapeClip) {

    beginFill(0xFF0000, 100);

    moveTo(0, 0);

    lineTo(100, 0);

    lineTo(100, 100);

    lineTo(0, 100);

    lineTo(0, 0);

    endFill();

    }

    // position the shape on the Stage

    shapeClip._x = 100;

    shapeClip._y = 100;

    // click the mouse to increase the strength

    shapeClip.onPress = function():Void {

    bevel.strength += 2;

    shapeClip.filters = [bevel];

    };

    // define a listener to modify the filter when pointer moves

    var mouseListener:Object = new Object();

    mouseListener.onMouseMove = function():Void {

    bevel.distance = (_xmouse / Stage.width) * 10;

    bevel.blurX = (_ymouse / Stage.height) * 10;

    bevel.blurY = bevel.blurX;

    shapeClip.filters = [bevel];

    };

    Mouse.addListener(mouseListener);

    The first section of code defines a BevelFilter instance, and uses the Drawing API to draw a square on the Stage. When you click the square on the Stage, the current strength value of the bevel increments and gives the bevel a taller, sharper appearance. The second section of code defines a mouse listener, which modifies the bevel's distance and blurring based on the current position of the mouse pointer.

  3. Select Control > Test Movie to test the Flash document.

When you move the mouse pointer along the x-axis, the offset distance of the bevel increases or decreases. When you move the mouse pointer along the y-axis, the mouse pointer's current coordinates modifies the amount of horizontal and vertical blurring.
 

About the gradient bevel filter

TOP

The gradient bevel filter is applied to an object as a rectangle, with the colors of the gradient distributed to three portions of the rectangle: two bevel edges (a highlight and a shadow) and an area we'll call the base fill. The following diagrams depicts the rectangle, with the bevel type set to inner. In the rectangle on the left, the dark gray areas are the bevel edges, and the light gray area is the base fill. In the rectangle on the right, a rainbow gradient bevel, with a four-color bevel on each edge, is applied.

The different properties of the gradient bevel filter control the way the filter is applied. The colors of the gradient bevel are set in the colors array. The actual distribution of colors in each portion of the rectangle is determined by the ratios array. The distance property determines the offset distance, or how many pixels away from the object the bevel edge is applied. The blurX and blurY properties control the sharpness of the colors in the bevel; higher values effectively make the bevel wider and softer, while lower values make the bevel thinner and sharper. The angle property is the theoretical light source falling on the object, thus causing a highlight and shadow effect on the object's edges. The strength property controls the spread of the colors: a lower strength value mutes the colors, as in the example; a higher strength value makes the outer numbers in the array stronger, forcing the middle colors in the array to be less prominent. Finally, knockout and type properties determine how and where the bevel filter is applied to the whole object: whether the filter knocks out the object and where it is placed.

One of the more complicated concepts to apply in the gradient bevel filter is the color distribution. To understand how the colors in a gradient bevel are distributed, think first of the colors you want in your gradient bevel. Because a simple bevel has the understood concepts of highlight color and shadow color, you can apply the same concepts to understand the gradient bevel filter: you have a highlight gradient and a shadow gradient. The highlight appears on the top left corner, and the shadow appears on the bottom right corner. There are four colors in the highlight and four in the shadow. However, you have to add another color (the base fill color), which appears where the edges of the highlight and shadow meet. There are nine colors for the colors array, which you can see in the previous diagram.

The number of colors in the colors array determine the number of elements in the alphas and ratios array. The first item in the colors array corresponds to the first item in the alphas array and in the ratios array, and so on. Because you have nine colors, you also have nine values in the alphas array and nine in the ratios array. The alpha values set the alpha transparency value of the colors.

The ratio values in the ratios array can range from 0 to 255 pixels. The middle value is 128; 128 is the base fill value. For most usages, to get the bevel effect you want, you should assign the ratio values as follows, using the example of nine colors:

  • The first four colors range from 0 through 127, increasing in value so each value is greater than or equal to the previous one. This is the first bevel edge, say, our highlight.

  • The fifth color (the middle color) is the base fill, set to 128. The pixel value of 128 sets the base fill, which appears either outside the shape (and around the bevel edges) if type is set to outer; or inside the shape, effectively covering the object's own fill, if the type is set to inner.

  • The last four colors range from 129 through 255, increasing in value so each value is greater than or equal to the previous one. This is the second bevel edge, for example, your shadow.

If you think of a gradient as composed of stripes of various colors, blending into each other, each ratio value sets the number of pixels for the associated color, thus setting the width of the color stripe in the gradient. If you want an equal distribution of colors for each edge:

  • Use an odd number of colors, where the middle color is the base fill.

  • Distribute the values between 0 through 127 and 129 through 255 equally among your colors.

  • Adjust the value to change the width of each stripe of color in the gradient.

NOTE : The angle value determines which edge is the highlight and which edge is the shadow.

The angle value determines the angle at which the gradient colors are applied to the object; meaning, where the highlight and shadow appear on the object. The colors are applied in the same order as the array.

The following code takes a pink square (drawn with the Drawing API) and applies a rainbow gradient filter. The colors, in the order in which they are present in the array, are: blue, green, purple, and yellow (highlight); red (base fill); yellow, purple, green, black (shadow). To determine the ratios values, we assign four highlight colors values from 0 to 127, making them roughly equal, and shadow colors from 129 to 255. The colors on the outer edges, blue (16) and black (235).

var colors:Array = [0x0000FF, 0x00FF00, 0x9900FF, 0xFFFF00, 0xFF0000, 0xFFFF00, 0x9900FF, 0x00FF00,0x000000];

var alphas:Array = [1, 1, 1, 1, 1, 1, 1, 1, 1];

var ratios:Array = [16, 32, 64, 96, 128, 160, 192, 224, 235];

var gradientBevel:GradientBevelFilter = new GradientBevelFilter(8, 225, colors, alphas, ratios, 16, 16, 1.3, 2, "inner", false);

The following figure shows the gradient bevel filter created by the code above, a nine-color rainbow bevel applied to a red rectangle movie clip:]

The dashed line shows how angles are determined. The figure shows how the angle of 225˚ is realized on the filter, and also shows each ratio value for each color. Setting the angle at 225˚ indicates that the first color in the array begins at 225˚, which is in the top left corner (the highlight). The dotted line shows where the highlight gradient is applied and where the shadow gradient is applied.

The original movie clip color is pink, but setting the 128 value to red means the 128-pixel value is the base fill and covers the original movie clip fill. However, when you set the filters property, the original object is not altered; by simply clearing the filters property, you can restore the original movie clip fill.

The properties of all filters affect each other, so if you adjust one property to change the effect that you're applying, you might need to adjust another property as well.

The full ActionScript code to create the previous figure is as follows:

import flash.filters.GradientBevelFilter;

// draws a filled square shape

this.createEmptyMovieClip("square_mc", this.getNextHighestDepth());

square_mc.beginFill(0xFF99CC);

square_mc.moveTo(40, 40);

square_mc.lineTo(200, 40);

square_mc.lineTo(200, 200);

square_mc.lineTo(40, 200);

square_mc.lineTo(40, 40);

square_mc.endFill();

/* GradientBevelFilter(distance:Number, angle:Number, colors:Array, alphas:Array, ratios:Array, blurX:Number, blurY:Number, strength:Number, quality:Number, type:String, knockout:Boolean) */

// create colors, alphas, and ratios arrays

var colors:Array = [0x0000FF, 0x00FF00, 0x9900FF, 0xFFFF00, 0xFF0000, 0xFFFF00, 0x9900FF, 0x00FF00,0x000000];//blue, green, purple, yellow, red, yellow, purple, green, black

var alphas:Array = [1, 1, 1, 1, 1, 1, 1, 1, 1];

var ratios:Array = [16, 32, 64, 96, 128, 160, 192, 224, 235];

// create the filter object

var gradientBevel:GradientBevelFilter = new GradientBevelFilter(8, 225, colors, alphas, ratios, 16, 16, 1.3, 2, "inner", false);

// apply the filter to the square movie clip

square_mc.filters = [gradientBevel];
 

Applying a gradient bevel filter

TOP

The GradientBevelFilter class lets you apply a gradient bevel effect to objects in Flash. A gradient bevel is a beveled edge that's enhanced with gradient color on the outside, inside, or top of an object. Beveled edges bring a three-dimensional look to objects, and can have colorful results as shown in the following figure.

The following procedure uses the Drawing API to draw a square on the Stage, and applies a gradient bevel filter to the shape.

To use the gradient bevel filter:

  1. Create a new Flash document and save it as gradientbevel.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import flash.filters.GradientBevelFilter;

    var shapeClip:MovieClip = this.createEmptyMovieClip("shape_mc", 1);

    with (shapeClip) {

    beginFill(0xFF0000, 100);

    moveTo(0, 0);

    lineTo(200, 0);

    lineTo(200, 200);

    lineTo(0, 200);

    lineTo(0, 0);

    endFill();

    }

    shapeClip._x = (Stage.width - shapeClip._width) / 2;

    shapeClip._y = (Stage.height - shapeClip._height) / 2;

    var colors:Array = new Array(0xFFFFFF, 0xCCCCCC, 0x000000);

    var alphas:Array = new Array(1, 0, 1);

    var ratios:Array = new Array(0, 128, 255);

    var gradientBevel:GradientBevelFilter = new GradientBevelFilter(10, 45, colors, alphas, ratios, 4, 4, 5, 3);

    var mouseListener:Object = new Object();

    mouseListener.onMouseDown = function() {

    gradientBevel.strength++;

    shapeClip.filters = [gradientBevel];

    };

    mouseListener.onMouseMove = function() {

    gradientBevel.blurX = (_xmouse / Stage.width) * 255;

    gradientBevel.blurY = (_ymouse / Stage.height) * 255;

    shapeClip.filters = [gradientBevel];

    };

    Mouse.addListener(mouseListener);

    This code uses the Drawing API to draw a square on the Stage, which is placed at the center of the Stage. When you move the mouse pointer around the Stage, the amount of blurring along the x-axis and y-axis increases or decreases. When you move your pointer towards the left of the Stage, the amount of horizontal blurring decreases. When you move the pointer towards the right of the Stage, the blurring increases. Similarly, the higher the pointer is on the Stage, the smaller the amount of blurring that occurs along the y-axis.]

  3. Select Control > Test Movie to test the document and view the results.
     

Using the color matrix filter

TOP

The ColorMatrixFilter class lets you apply a 4 x 5 matrix transformation on the ARGB color and alpha values of every pixel on the input image to produce a result with a new set of ARGB color and alpha values. This filter allows hue (distinct color or shade) rotation, saturation (intensity of a specific hue) changes, luminance (brightness or intensity of a color) to alpha, and various other effects. Also, you can animate these filters to create effects in your applications.

NOTE : You can apply the color matrix filter to bitmaps and movie clip instances.

You can use the color matrix filter to modify the brightness of an instance, as the following example demonstrates.

To increase the brightness of a movie clip:

  1. Create a new Flash document and save it as brightness.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import flash.filters.ColorMatrixFilter;

    System.security.allowDomain

    var mcl_obj:Object = new Object();

    mcl_obj.onLoadInit = function(target_mc:MovieClip):Void {

    var myElements_array:Array = [1, 0, 0, 0, 100,

    0, 1, 0, 0, 100,

    0, 0, 1, 0, 100,

    0, 0, 0, 1, 0];

    var myColorMatrix_filter:ColorMatrixFilter = new ColorMatrixFilter(myElements_array);

    target_mc.filters = [myColorMatrix_filter];

    }

    this.createEmptyMovieClip("img_mc", this.getNextHighestDepth());

    var img_mcl:MovieClipLoader = new MovieClipLoader();

    img_mcl.addListener(mcl_obj);

    img_mcl.loadClip("http://www.helpexamples.com/flash/images/image2.jpg", img_mc);

    This code dynamically loads a JPEG image by using a MovieClipLoader instance. After the image is completely loaded and is placed on the Stage, the instance's brightness is set to 100% byusing a color matrix filter.

  3. Select Control > Test Movie to test the document.

You could also create an animated brightness effect by combining the Tween class with the ColorMatrixFilter class, as the next procedure shows.

To animate the brightness level of an instance by using the Tween class:

Create a new Flash document and save it as brightnesstween.fla.

Add the following ActionScript to Frame 1 of the Timeline:

import flash.filters.ColorMatrixFilter;

import mx.transitions.Tween;

import mx.transitions.easing.*;

System.security.allowDomain

var mclListener:Object = new Object();

mclListener.onLoadInit = function(target_mc:MovieClip):Void {

// center movie clip instance on Stage

  1. target_mc._x = (Stage.width - target_mc._width) / 2;

  2. target_mc._y = (Stage.height - target_mc._height) / 2;

    target_mc.watch("brightness", brightnessWatcher, target_mc);

    // animate the target_mc movie clip between -100 and +100 brightness

    var t:Object = new Tween(target_mc, "brightness", Elastic.easeOut, 100, -100, 3, true);

    t.onMotionFinished = function() {

    this.yoyo();

    };

    };

    this.createEmptyMovieClip("img_mc", 10);

    var img_mcl:MovieClipLoader = new MovieClipLoader();

    img_mcl.addListener(mclListener);

    img_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img_mc);

    function brightnessWatcher(prop:String, oldVal:Number, newVal:Number, target_mc:MovieClip):Number {

    var brightness_array:Array = [1, 0, 0, 0, newVal,

    0, 1, 0, 0, newVal,

    0, 0, 1, 0, newVal,\

    0, 0, 0, 1, 0];

    target_mc.filters = [new ColorMatrixFilter(brightness_array)];

    return newVal;

    };

    The first section of code uses the MovieClipLoader class to load a JPEG image onto the Stage. After the image completely loads, you reposition the image to the center of the Stage. Then you use the Tween class to animate the image brightness level. To animate the brightness, you use the Object.watch() method, which registers an event handler that you start when a specified property of an ActionScript object changes. Whenever some ActionScript tries to set the custom brightness property of the target_mc instance, you call the brightnessWatcher function. The custom brightnessWatcher function creates a new array, which uses the color matrix filter to set the target image's brightness to a specified amount.

  3. Select Control > Test Movie to test the document.

After the image loads and is placed on the Stage, the image's brightness animates between -100 and 100. After the brightness tween is complete, the animation is reversed using the Tween.yoyo() method, which causes the tween to constantly animate.
 

Using the convolution filter

TOP

The ConvolutionFilter class applies a matrix convolution filter effect. A convolution combines pixels in a source image that you specify with neighboring pixels to produce an image. You can achieve a wide variety of imaging operations by using the convolution filter, which includes blurring, edge detection, sharpening, embossing, and beveling effects.

NOTE : You can apply this filter on bitmaps and movie clip instances.

A matrix convolution is based on an n x m matrix, which describes how a given pixel value in the input image is combined with its neighboring pixel values to produce a resulting pixel value. Each resulting pixel is determined by applying the matrix to the corresponding source pixel and its neighboring pixels.

This filter is only available by using ActionScript. For more information on this filter, see ConvolutionFilter (flash.filters.ConvolutionFilter) in the ActionScript 2.0 Language Reference.
The following procedure applies the convolution filter to a dynamically loaded JPEG image.

To use the convolution filter to modify an image's color:

  1. Create a new Flash document and save it as convolution.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import flash.filters.ConvolutionFilter;

    import flash.display.BitmapData;

    this.createEmptyMovieClip("shape_mc", 1);

    shape_mc.createEmptyMovieClip("holder_mc", 1);

    var imageLoader:MovieClipLoader = new MovieClipLoader();

    imageLoader.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", shape_mc.holder_mc);

    var matrixArr:Array = [1, 4, 6, 4, 1, 4, 16, 24, 16, 4, 16, 6, 24, 36, 24, 6, 4, 16, 24, 16, 4, 1, 4, 6, 4, 1];

    var convolution:ConvolutionFilter = new ConvolutionFilter(5, 5, matrixArr);

    shape_mc.filters = [convolution];

    var mouseListener:Object = new Object();

    mouseListener.onMouseMove = function():Void {

    convolution.divisor = (_xmouse / Stage.width) * 271;

    convolution.bias = (_ymouse / Stage.height) * 100;

    shape_mc.filters = [convolution];

    };

    Mouse.addListener(mouseListener);

    The preceding code is separated into three sections. The first section imports two classes: ConvolutionFilter and BitmapData. The second section creates a nested movie clip and uses a movie clip loader object to load an image into the nested movie clip. A convolution filter object is created and applied to the shape_mc movie clip. The final section of code defines a mouse listener object that modifies the convolution filter's divisor and bias properties based on the current position of the mouse pointer and reapplies the convolution filter to the shape_mc movie clip.

  3. Select Control > Test Movie to test the Flash document.

Moving the mouse pointer along the x-axis of the Stage modifies the filter's divisor, whereas moving the mouse pointer along the y-axis of the Stage modifies the filter's bias.
 

Using the displacement map filter

TOP

The DisplacementMapFilter class uses the pixel values from the specified BitmapData object (called the displacement map image) to perform a displacement of an instance that's on the Stage, such as a movie clip instance or a bitmap data instance. You can use this filter to achieve a warped or mottled effect on a specified instance.

This filter is only available by using ActionScript. For more information on this filter, see DisplacementMapFilter (flash.filters.DisplacementMapFilter) in the ActionScript 2.0 Language Reference.

The following procedure loads a JPEG image and applies a displacement map filter to it, which causes the image to look distorted. Whenever the user moves the mouse, the displacement map is regenerated.

To distort an image with the displacement map filter:

  1. Create a new Flash document and save it as displacement.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import flash.filters.DisplacementMapFilter;

    import flash.geom.Point;

    import flash.display.BitmapData;

    var perlinBmp:BitmapData;

    var displacementMap:DisplacementMapFilter;

    var mclListener:Object = new Object();

    mclListener.onLoadInit = function(target_mc:MovieClip):Void {

    target_mc._x = (Stage.width - target_mc._width) / 2;

    target_mc._y = (Stage.height - target_mc._height) / 2;

    perlinBmp = new BitmapData(target_mc._width, target_mc._height);

    perlinBmp.perlinNoise(target_mc._width, target_mc._height, 10, Math.round(Math.random() * 100000), false, true, 1, false);

    displacementMap = new DisplacementMapFilter(perlinBmp, new Point(0, 0), 1, 1, 100, 100, "color");

    shapeClip.filters = [displacementMap];

    };

    var shapeClip:MovieClip = this.createEmptyMovieClip("shapeClip", 1);

    shapeClip.createEmptyMovieClip("holderClip", 1);

    var imageLoader:MovieClipLoader = new MovieClipLoader();

    imageLoader.addListener(mclListener);

    imageLoader.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", shapeClip.holderClip);

    var mouseListener:Object = new Object();

    mouseListener.onMouseMove = function():Void {

    perlinBmp.perlinNoise(shapeClip._width, shapeClip._height, 10, Math.round(Math.random() * 100000), false, true, 1, false);

    shapeClip.filters = [displacementMap];

    };

    Mouse.addListener(mouseListener);

    This code loads a JPEG image and places it on the Stage. After the image is completely loaded, this code creates a BitmapData instance and uses the perlinNoise() method to fill it with randomly placed pixels. The BitmapData instance passes to the displacement map filter, which is applied to the image and causes the image to look distorted.

  3. Select Control > Test Movie to test the document.

Move your mouse pointer around the Stage to re-create a displacement map by calling the perlinNoise() method, which changes the appearance of the JPEG image.
 

Manipulating filter effects with code

TOP

Flash Basic 8 and Flash Professional 8 let you dynamically add various filters to your movie clips, text fields, and buttons on the Stage, instead of having to add filters in the Flash Professional 8 authoring environment (using the Filters tab in the Property inspector). When you add and manipulate filters during playback, you can add realistic shadows, blurs, and glows that react to mouse movements or user events.

 

Adjusting filter properties

TOP

The array of filters applied to an object can be accessed through standard ActionScript calls by using the MovieClip.filters property. This process returns an array that contains each filter object currently associated with the MovieClip. Each filter has a set of properties unique to that filter. The filters can be accessed and modified just like an array object, although getting and setting the filters by using the filters property returns a duplicate of the filters object instead of a reference.

Setting the filters property duplicates the filters array passed in and does not store it as a reference. When getting the filters property, it returns a new copy of the array. One negative implication of this approach is that the following code does not work:

// does not work

my_mc.filters[0].blurX = 20;

Because the previous code snippet returns a copy of the filters array, the code modifies the copy instead of the original array. In order to modify the blurX property, you would need to use the following ActionScript code instead:

// works

var filterArray:Array = my_mc.filters;

filterArray[0].blurX = 20;

my_mc.filters = filterArray;

The following procedure blurs an image based on the current position of the mouse pointer on the Stage. Whenever the mouse pointer moves horizontally or vertically, the blurX and blurY properties of the blur filter are modified accordingly.

To adjust a movie clip's filter properties:

  1. Create a new Flash document and save it as adjustfilter.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import flash.filters.BlurFilter;

    this.createEmptyMovieClip("holder_mc", 10);

    holder_mc.createEmptyMovieClip("img_mc", 20);

    holder_mc.img_mc.loadMovie("http://www.helpexamples.com/flash/images/image2.jpg");

    holder_mc.filters = [new BlurFilter(10, 10, 2)];

    holder_mc._x = 75;

    holder_mc._y = 75;

    holder_mc.onMouseMove = function() {

    var tempFilter:BlurFilter = holder_mc.filters[0];

    tempFilter.blurX = Math.floor((_xmouse / Stage.width) * 255);

    tempFilter.blurY = Math.floor((_ymouse / Stage.height) * 255);

    holder_mc.filters = [tempFilter];

    };

    The previous code is split into three sections. The first section imports the flash.filters.BlurFilter class so that you don't have to use the fully qualified class name when you refer to the BlurFilter class. The second section of code creates a couple of movie clips and loads an image into one of the nested clips. The third section of code responds to the mouse movement on the Stage and adjusts the blur accordingly.

  3. Select Control > Test Movie to test the Flash document.

Moving the mouse pointer along the x-axis modifies the blur filter's blurX property. Moving the mouse pointer along the y-axis modifies the blur filter's blurY property. The closer the mouse pointer is to the upper-left corner of the Stage, the less blurring is applied to the movie clip.
 

Animating a filter by using ActionScript

TOP

You can use ActionScript, such as the Tween class, to animate filters at runtime, which lets you apply interesting, animated effects to your Flash applications.

In the following example, you see how to combine the BlurFilter with the Tween class to create an animated blur that modifies the Blur filter between a value of 0 and 10 at runtime.

To animate blurs using the Tween class:

  1. Create a new Flash document and save it as animatedfilter.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import flash.filters.BlurFilter;

    import mx.transitions.Tween;

    import mx.transitions.easing.*;

    this.createEmptyMovieClip("holder_mc", 10);

    holder_mc.createEmptyMovieClip("img_mc", 20);

    var mclListener:Object = new Object();

    mclListener.onLoadInit = function(target_mc:MovieClip) {

    target_mc._x = (Stage.width - target_mc._width) / 2;

    target_mc._y = (Stage.height - target_mc._height) / 2;

    var myTween:Tween = new Tween(target_mc, "blur", Strong.easeInOut, 0, 20, 3, true);

    myTween.onMotionChanged = function() {

    target_mc._parent.filters = [new BlurFilter(target_mc.blur, target_mc.blur, 1)];

    };

    myTween.onMotionFinished = function() {

    myTween.yoyo();

    }

    };

    var my_mcl:MovieClipLoader = new MovieClipLoader();

    my_mcl.addListener(mclListener);

    my_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", holder_mc.img_mc);

    The preceding code is separated into three sections. The first section imports the required classes and packages. The second section creates a nested movie clip that is used to load an image and apply filters to the holder movie clip. The final section of code creates a new MovieClipLoader instance and a listener for the movie clip loader. The listener object defines a single event handler function, onLoadInit, that is started once the image successfully loads and is available on the Stage. First the image is repositioned to the center of the Stage, then a new Tween object is created that animates the movie clip and applies a blur filter of 0 and 10.

  3. Select Control > Test Movie to test the Flash document.
     

Using the clone() method

TOP

The clone() method within each filter class returns a new filter instance with all of the same properties as the original filter instance. When you work with filters, you might want to make a copy of a filter, and to do so you need to duplicate the filter using the clone() method. If you do not use the clone method to duplicate a filter, Flash creates a reference to the original filter only. If Flash creates a reference to the original filter, any change made to the duplicate filter also modifies the original filter object.

The following procedure creates a new instance of a DropShadowFilter (greenDropShadow), calls the clone() method to duplicate the green drop shadow filter, and saves a new filter named redDropShadow. The cloned filter sets a new drop shadow color, and both filters are applied to a flower_mc movie clip instance that's on the Stage.

To use the clone method:

  1. Create a new Flash document, and name it clone.fla.

  2. Create a movie clip on the Stage.

  3. Select the movie clip instance, and type flower_mc in the Instance Name text box in the Property inspector.

  4. Select Frame 1 of the Timeline, and add the following code in the Actions panel:

    import flash.filters.DropShadowFilter;

    var greenDropShadow:DropShadowFilter = new DropShadowFilter();

    greenDropShadow.color = 0x00FF00; // green

    var redDropShadow:DropShadowFilter = greenDropShadow.clone();

    redDropShadow.color = 0xFF0000; // red

    flower_mc.filters = [greenDropShadow, redDropShadow];]

    The preceding code creates a new instance of the drop shadow filter and gives it the name greenDropShadow. The green drop shadow object is duplicated by using the DropShadowFilter.clone() method and creates a new filter object called redDropShadow. Both the green drop shadow and red drop shadow filters are applied to the flower_mc movie clip instance on the Stage. If you did not call the clone() method, both drop shadows would appear red. The reason for this appearance is that setting the redDropShadow.color property changes both the red drop shadow and green drop shadow objects because the red drop shadow contains a reference to the green drop shadow.

  5. Select Control > Test Movie to test the Flash document.

The filter is duplicated and cloned, and both filters are applied to the flower_mc instance.

 

Creating bitmaps with the BitmapData class

TOP

The BitmapData class lets you create arbitrarily sized transparent or opaque bitmap images, then manipulate them in various ways at runtime. When you manipulate a BitmapData instance directly by using ActionScript, you can create very complex images without incurring the overhead of constantly redrawing the content from vector data in Flash Player. The methods of the BitmapData class support a variety of effects that are not available through the Filters tab in the Flash workspace.

A BitmapData object contains an array of pixel data. This data either can represent a fully opaque bitmap or a transparent bitmap that contains alpha channel data. Either type of BitmapData object is stored as a buffer of 32-bit integers. Each 32-bit integer determines the properties of a single pixel in the bitmap. Each 32-bit integer is a combination of four 8-bit channel values (from 0 to 255) that describe the alpha transparency and the red, green, and blue (ARGB) values of the pixel.

The following procedure dynamically loads a JPEG image onto the Stage, and uses the BitmapData class to create a noise effect, similar to static on a television. The noise effect is redrawn with a random pattern every 100 milliseconds (1/10 of a second). Moving the mouse pointer along the x-axis and y-axis affects how much static is drawn at every interval.

To create a noise effect with the BitmapData class:

  1. Create a new Flash document and save it as noise.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import flash.display.BitmapData;

    this.createTextField("status_txt", 90, 0, 0, 100, 20);

    status_txt.selectable = false;

    status_txt.background = 0xFFFFFF;

    status_txt.autoSize = "left";

    function onMouseMove() {

    status_txt._x = _xmouse;

    status_txt._y = _ymouse-20;

    updateAfterEvent();

    }

    this.createEmptyMovieClip("img_mc", 10);

    img_mc.loadMovie("http://www.helpexamples.com/flash/images/image1.jpg");

    var noiseBmp:BitmapData = new BitmapData(Stage.width, Stage.height, true);

    this.attachBitmap(noiseBmp, 20);

    setInterval(updateNoise, 100);

    var grayScale:Boolean = true;

    function updateNoise():Void {

    var low:Number = 30 * _xmouse / Stage.width;

    var high:Number = 200 * _ymouse / Stage.height;

    status_txt.text = "low:" + Math.round(low) + ", high:" + Math.round(high);

    noiseBmp.noise(Math.round(Math.random() * 100000), low, high, 8, true);

    }

    This code creates a text field with the instance name status_txt, which follows the mouse pointer and displays the current values for the high and low parameters for the noise() method. ThesetInterval() function changes the noise effect, which is updated every 100 milliseconds (1/10 of a second), by continuously calling the updateNoise() function. The high and low parameters for the noise() method are determined by calculating the pointer's current position on the Stage.

  3. Select Control > Test Movie to test the document.

Moving the mouse pointer along the x-axis affects the low parameter; moving the mouse pointer along the y-axis affects the high parameter.

The BitmapData class also lets you distort a dynamically loaded image by using a combination of a perlinNoise() method effect and a displacement map filter. The following procedure shows this.

To apply a displacement map filter to an image:

  1. Create a new Flash document and save it as displacement.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    // Import classes.

    import flash.filters.DisplacementMapFilter;

    import flash.display.BitmapData;

    import flash.geom.Point;

    // Create a clip and a nested clip.

    var shapeClip:MovieClip = this.createEmptyMovieClip("shapeClip", 1);

    shapeClip.createEmptyMovieClip("holderClip", 1);

    // Load JPEG.

    var imageLoader:MovieClipLoader = new MovieClipLoader();

    imageLoader.loadClip("http://www.helpexamples.com/flash/images/image4.jpg", shapeClip.holderClip);

    // Create BitmapData instance.

    var perlinBmp:BitmapData = new BitmapData(Stage.width, Stage.height);

    perlinBmp.perlinNoise(Stage.width, Stage.height, 10, Math.round(Math.random() * 100000), false, true, 1, false);

    // Create and apply the displacement map filter.

    var displacementMap:DisplacementMapFilter = new DisplacementMapFilter(perlinBmp, new Point(0, 0), 1, 1, 100, 100, "color", 1);

    shapeClip.filters = [displacementMap];

    // Create and apply a listener.

    var mouseListener:Object = new Object();

    mouseListener.onMouseMove = function():Void {

    perlinBmp.perlinNoise(Stage.width, Stage.height, 10, Math.round(Math.random() * 100000), false, true, 1, false);

    shapeClip.filters = [displacementMap];

    }

    Mouse.addListener(mouseListener);]

    This code example consists of five logical sections. The first section imports the necessary classes for the example. The second block of code creates a nested movie clip and loads a JPEG image from a remote server. The third block of code creates a new BitmapData instance named perlinBmp, which is the same size as the dimensions of the Stage. The perlinBmp instance contains the results of a Perlin noise effect, and is used later as a parameter for the displacement map filter. The fourth block of code creates and applies the displacement map filter effect to the dynamically loaded image created earlier. The fifth, and final, block of code creates a listener for the mouse that regenerates the Perlin noise that the displacement map filter uses whenever the user moves the mouse pointer.

  3. Select Control > Test Movie to test the Flash document.
     

About blending modes

TOP

You can apply blend modes to movie clip objects by using the Flash workspace (Flash Professional 8) or ActionScript (Flash Basic 8 and Flash Professional 8). At runtime, multiple graphics are merged as one shape. For this reason, you cannot apply different blend modes to different graphic symbols.

For more information on using ActionScript to apply blend modes,

Blend modes involve combining the colors of one image (the base image) with the colors of another image (the blend image) to produce a third image. Each pixel value in an image is processed with the corresponding pixel value of the other image to produce a pixel value for that same position in the result.

The MovieClip.blendMode property supports the following blend modes:

add Commonly used to create an animated lightening dissolve effect between two images.

alpha Commonly used to apply the transparency of the foreground on the background.

darken Commonly used to superimpose type.

difference Commonly used to create more vibrant colors.

erase Commonly used to cut out (erase) part of the background using the foreground alpha.

hardlight Commonly used to create shading effects.

invert Used to invert the background.

layer Used to force the creation of a temporary buffer for precomposition for a particular movie clip.

lighten Commonly used to superimpose type.

multiply Commonly used to create shadows and depth effects.

normal Used to specify that the pixel values of the blend image override those of the base image.

overlay Commonly used to create shading effects.

screen Commonly used to create highlights and lens flares.

subtract Commonly used to create an animated darkening dissolve effect between two images.
 

Applying blending modes

TOP

The following procedure loads a dynamic image and lets you apply different blend modes to the image by selecting a blending mode from a combo box on the Stage.

To apply different blending modes to an image:

  1. Create a new Flash document and save it as blendmodes.fla.

  2. Drag a ComboBox component instance onto the Stage and give it an instance name of blendMode_cb.

  3. Add the following ActionScript to Frame 1 of the Timeline:

    var blendMode_dp:Array = new Array();

    blendMode_dp.push({data:"add", label:"add"});

    blendMode_dp.push({data:"alpha", label:"alpha"});

    blendMode_dp.push({data:"darken", label:"darken"});

    blendMode_dp.push({data:"difference", label:"difference"});

    blendMode_dp.push({data:"erase", label:"erase"});

    blendMode_dp.push({data:"hardlight", label:"hardlight"});

    blendMode_dp.push({data:"invert", label:"invert"});

    blendMode_dp.push({data:"layer", label:"layer"});

    blendMode_dp.push({data:"lighten", label:"lighten"});

    blendMode_dp.push({data:"multiply", label:"multiply"});

    blendMode_dp.push({data:"normal", label:"normal"});

    blendMode_dp.push({data:"overlay", label:"overlay"});

    blendMode_dp.push({data:"screen", label:"screen"});

    blendMode_dp.push({data:"subtract", label:"subtract"});

    blendMode_cb.dataProvider = blendMode_dp;

    var mclListener:Object = new Object();

    mclListener.onLoadInit = function(target_mc:MovieClip) {

    var blendModeClip:MovieClip = target_mc.createEmptyMovieClip("blendModeType_mc", 20);

    with (blendModeClip) {

    beginFill(0x999999);

    moveTo(0, 0);

    lineTo(target_mc._width / 2, 0);

    lineTo(target_mc._width / 2, target_mc._height);

    lineTo(0, target_mc._height);

    lineTo(0, 0);

    endFill();

    }

    target_mc._x = (Stage.width - target_mc._width) / 2;

    target_mc._y = (Stage.height - target_mc._height) / 2;

    blendModeClip.blendMode = blendMode_cb.value;

    };

    this.createEmptyMovieClip("img_mc", 10);

    var img_mcl:MovieClipLoader = new MovieClipLoader();

    img_mcl.addListener(mclListener);

    img_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img_mc);

    function cbListener(eventObj:Object):Void {

    img_mc.blendModeType_mc.blendMode = eventObj.target.value;

    }

    blendMode_cb.addEventListener("change", cbListener);

    This ActionScript code populates the combo box with each type of blending mode, so the user can view each effect on the dynamically loaded image. A listener object is created, which is used with a MovieClipLoader instance. The listener object defines a single event listener, onLoadInit, which is invoked when the image is completely downloaded and is initialized by Flash. The event listener creates a new movie clip named blendModeType_mc, and uses the Drawing API to draw a rectangular shape over the left half of the image. The currently selected blending mode for the ComboBox instance is then applied to the blendModeType_mc movie clip.

    The rest of the code sets up the MovieClipLoader instance, which is responsible for loading the specified image into a movie clip on the Stage. Finally, a listener is defined for the blendMode_cb ComboBox instance, which applies the selected blending mode whenever a new item is selected from the ComboBox instance.

  4. Select Control > Test Movie to test the document.
     

About operation order

TOP

The following list is the order of operations in which a filters array, blend modes, color transforms, and mask layers are attached or performed for a movie clip instance:

  1. The movie clip's bitmap is updated from vector content (the cacheAsBitmap property is set to true).

  2. If you use the setMask() method, and the mask has a bitmap cache, Flash performs an alpha blend between the two images.

  3. Filters are then applied (blur, drop shadow, glow, and so on.)

  4. If you use the ColorTransform class, the color transform operation is performed and cached as bitmap result.

  5. If you apply a blending mode, the blend is then performed (using a vector renderer).

  6. If you apply external masking layers, the layers perform masking (using a vector renderer).
     

Drawing with ActionScript

TOP

You can use methods of the MovieClip class to draw lines and fills on the Stage. This lets you create drawing tools for users and draw shapes in the SWF file in response to events. The following are the MovieClip class drawing methods:

  • beginFill()

  • beginGradientFill()

  • clear()

  • curveTo()

  • endFill()

  • lineTo()

  • lineStyle()

  • moveTo()

You can use the drawing methods with any movie clip. However, if you use the drawing methods with a movie clip that was created in authoring mode, the drawing methods execute before the clip is drawn. In other words, content that is created in authoring mode is drawn on top of content drawn with the drawing methods.

You can use movie clips with drawing methods as masks; however, as with all movie clip masks, strokes are ignored.

 

Using drawing methods to draw lines, curves, and shapes

TOP

You can use the Flash Drawing API to dynamically create shapes on the Stage at runtime. You can use these shapes to dynamically mask content, apply filters to them, or animate them around the Stage. You can also use the Drawing API to create various drawing tools, which let users use the mouse or keyboard to draw shapes on the SWF file.

To draw a line:

  1. Create a new Flash document and save it as line.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    this.createEmptyMovieClip("line_mc", 10);

    line_mc.lineStyle(1, 0x000000, 100);

    line_mc.moveTo(0, 0);

    line_mc.lineTo(200, 100);

    line_mc._x = 100;

    line_mc._y = 100;

    This code draws a line from 0,0 on the Stage to 200,100. The line's _x and _y coordinates are then modified to reposition the line to 100,100 on the Stage.

  3. Save your Flash document and select Control > Test Movie to test the SWF file.

To draw a more complex shape, continue calling the MovieClip.lineTo() method and draw a rectangle, square, or oval, as the following procedures show.

To draw a curve:

  1. Create a new Flash document and save it as curve.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    this.createEmptyMovieClip("circle_mc", 1);

    with (circle_mc) {

    lineStyle(4, 0x000000, 100);

    beginFill(0xFF0000);

    moveTo(200, 300);

    curveTo(300, 300, 300, 200);

    curveTo(300, 100, 200, 100);

    curveTo(100, 100, 100, 200);

    curveTo(100, 300, 200, 300);

    endFill();

    }

  3. Save your Flash document and select Control > Test Movie to test the Flash document.

This code uses the Drawing API to draw a circle on the Stage. The circle shape uses only four calls to the MovieClip.curveTo() method and therefore can look a little distorted. For another example that uses the Drawing API to create a circle, see the procedure on creating a circle under Drawing specific shapes for code that uses eight calls to the MovieClip.curveTo() method to draw a more realistic circle.

To draw a triangle:

  1. Create a new Flash document and save it as triangle.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    this.createEmptyMovieClip("triangle_mc", 1);

    This code uses the MovieClip.createEmptyMovieClip() method to create an empty movie clip on the Stage. The new movie clip is a child of an existing movie clip (in this case, the main timeline).

  3. Add the following ActionScript to Frame 1 of the Timeline, following the code you added in the preceding step:

    with (triangle_mc) {

    lineStyle(5, 0xFF00FF, 100);

    moveTo(200, 200);

    lineTo(300, 300);

    lineTo(100, 300);

    lineTo(200, 200);

    }

    In this code, the empty movie clip (triangle_mc) calls drawing methods. This code draws a triangle with 5-pixel purple lines and no fill.

  4. Save your Flash document and select Control > Test Movie to test the Flash document.

     

Drawing specific shapes

TOP

This section shows you how to create some more flexible methods that you can use to draw more advanced shapes, such as rounded rectangles and circles.

To create a rectangle:

  1. Create a new Flash document and save it as rect.fla.

  2. Add the following ActionScript code to Frame 1 of the Timeline:

    this.createEmptyMovieClip("rectangle_mc", 10);

    rectangle_mc._x = 100;

    rectangle_mc._y = 100;

    drawRectangle(rectangle_mc, 240, 180, 0x99FF00, 100);

    function drawRectangle(target_mc:MovieClip, boxWidth:Number, boxHeight:Number, fillColor:Number, fillAlpha:Number):Void {

    with (target_mc) {

    beginFill(fillColor, fillAlpha);

    moveTo(0, 0);

    lineTo(boxWidth, 0);

    lineTo(boxWidth, boxHeight);

    lineTo(0, boxHeight);

    lineTo(0, 0);

    endFill();

    }

    }

  3. Save your Flash document and select Control > Test Movie to test the Flash document.

Flash draws a simple green rectangle on the Stage and positions it at 100,100. To change the dimensions of the rectangle, or its fill color or transparency, you can change those values within

the call to the drawRectangle() method instead of having to modify the contents of the MovieClip.beginFill() method.

You can also create a rectangle with rounded corners using the Drawing API, as the following procedure shows.

To create a rounded rectangle:

  1. Create a new Flash document and save it as roundrect.fla.

  2. Add the following ActionScript code to Frame 1 of the Timeline:

    this.createEmptyMovieClip("rectangle_mc", 10);

    rectangle_mc._x = 100;

    rectangle_mc._y = 100;

    drawRoundedRectangle(rectangle_mc, 240, 180, 20, 0x99FF00, 100);

    function drawRoundedRectangle(target_mc:MovieClip, boxWidth:Number, boxHeight:Number, cornerRadius:Number, fillColor:Number, fillAlpha:Number):Void {

    with (target_mc) {

    beginFill(fillColor, fillAlpha);

    moveTo(cornerRadius, 0);

    lineTo(boxWidth - cornerRadius, 0);

    curveTo(boxWidth, 0, boxWidth, cornerRadius);

    lineTo(boxWidth, cornerRadius);

    lineTo(boxWidth, boxHeight - cornerRadius);

    curveTo(boxWidth, boxHeight, boxWidth - cornerRadius, boxHeight);

    lineTo(boxWidth - cornerRadius, boxHeight);

    lineTo(cornerRadius, boxHeight);

    curveTo(0, boxHeight, 0, boxHeight - cornerRadius);

    lineTo(0, boxHeight - cornerRadius);

    lineTo(0, cornerRadius);

    curveTo(0, 0, cornerRadius, 0);

    lineTo(cornerRadius, 0);

    endFill();

    }

    }

  3. Save the Flash document and select Control > Test Movie to test the document.

A green rectangle appears on the Stage that is 240 pixels wide and 180 pixels high with 20-pixel rounded corners. You can create multiple instances of rounded rectangles by creating new

movie clips using MovieClip.createEmptyMovieClip() and calling your custom drawRoundedRectangle() function.

You can create a perfect circle using the Drawing API, as the following procedure shows.

To create a circle:

  1. Create a new Flash document and save as circle2.fla.

  2. Add the following ActionScript code to Frame 1 of the Timeline:

    this.createEmptyMovieClip("circle_mc", 10);

    circle_mc._x = 100;

    circle_mc._y = 100;

    drawCircle(circle_mc, 100, 0x99FF00, 100);

    function drawCircle(target_mc:MovieClip, radius:Number, fillColor:Number, fillAlpha:Number):Void {

    var x:Number = radius;

    var y:Number = radius;

    with (target_mc) {

    beginFill(fillColor, fillAlpha);

    moveTo(x + radius, y);

    curveTo(radius + x, Math.tan(Math.PI / 8) * radius + y, Math.sin(Math.PI / 4) * radius + x, Math.sin(Math.PI / 4) * radius + y);

    curveTo(Math.tan(Math.PI / 8) * radius + x, radius + y, x, radius + y);

    curveTo(-Math.tan(Math.PI / 8) * radius + x, radius+ y, -Math.sin(Math.PI / 4) * radius + x, Math.sin(Math.PI / 4) * radius + y);

    curveTo(-radius + x, Math.tan(Math.PI / 8) * radius + y, -radius + x, y);

    curveTo(-radius + x, -Math.tan(Math.PI / 8) * radius + y, -Math.sin(Math.PI / 4) * radius + x, -Math.sin(Math.PI / 4) * radius + y);

    curveTo(-Math.tan(Math.PI / 8) * radius + x, -radius + y, x, -radius + y);

    curveTo(Math.tan(Math.PI / 8) * radius + x, -radius + y, Math.sin(Math.PI / 4) * radius + x, -Math.sin(Math.PI / 4) * radius + y);

    curveTo(radius + x, -Math.tan(Math.PI / 8) * radius + y, radius + x, y);

    endFill();

    }

    }

  3. Save your Flash document and select Control > Test Movie to test the SWF file.

This code creates a more complex, and realistic, circle than the previous circle example. Instead of only using four calls to the curveTo() method, this example uses eight calls to the

curveTo() method, which gives the shape a much rounder appearance.

You can use the Drawing API to create a triangle, as the following procedure shows.

To create a fancy triangle:

  1. Create a new Flash document and save it as fancytriangle.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    this.createEmptyMovieClip("triangle_mc", 10);

    triangle_mc._x = 100;

    triangle_mc._y = 100;

    drawTriangle(triangle_mc, 100, 0x99FF00, 100);

    function drawTriangle(target_mc:MovieClip, sideLength:Number, fillColor:Number, fillAlpha:Number):Void {

    var tHeight:Number = sideLength * Math.sqrt(3) / 2;

    with (target_mc) {

    beginFill(fillColor, fillAlpha);

    moveTo(sideLength / 2, 0);

    lineTo(sideLength, tHeight);

    lineTo(0, tHeight);

    lineTo(sideLength / 2, 0);

    endFill();

    }

    }

    The Drawing API draws an equilateral triangle on the Stage and fills it with the specified fill color and amount of alpha (transparency).

  3. Save the Flash document and select Control > Test Movie to test the Flash document.

     

Using complex gradient fills

TOP

The Flash Drawing API supports gradient fills as well as solid fills. The following procedure creates a new movie clip on the Stage, use the Drawing API to create a square, and then fills the square with a radial red and blue gradient.

To create a complex gradient:

  1. Create a new Flash document and save it as radialgradient.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    this.createEmptyMovieClip("gradient_mc", 10);

    var fillType:String = "radial";

    var colors:Array = [0xFF0000, 0x0000FF];

    var alphas:Array = [100, 100];

    var ratios:Array = [0, 0xFF];

    var matrix:Object = {a:200, b:0, c:0, d:0, e:200, f:0, g:200, h:200, i:1};

    var spreadMethod:String = "reflect";

    var interpolationMethod:String = "linearRGB";

    var focalPointRatio:Number = 0.9;

    with (gradient_mc) {

    beginGradientFill(fillType, colors, alphas, ratios, matrix, spreadMethod, interpolationMethod, focalPointRatio);

    moveTo(100, 100);

    lineTo(100, 300);

    lineTo(300, 300);

    lineTo(300, 100);

    lineTo(100, 100);

    endFill();

    }

    The preceding ActionScript code uses the Drawing API to create a square on the Stage and calls the beginGradientFill() method to fill the square with a red and blue circular gradient.

  3. Save the Flash document and select Control > Test Movie to view the Flash file.
     

Using line styles

TOP

The Flash Drawing API lets you specify a line style that Flash uses for subsequent calls to MovieClip.lineTo() and MovieClip.curveTo() until you call MovieClip.lineStyle() with different parameters, as follows:

lineStyle(thickness:Number, rgb:Number, alpha:Number, pixelHinting:Boolean, noScale:String, capsStyle:String, jointStyle:String, miterLimit:Number)

You can call MovieClip.lineStyle() in the middle of drawing a path to specify different styles for different line segments within a path.

 

Setting stroke and caps styles

TOP

Flash 8 includes several improvements to line drawing. New line parameters added in Flash Player 8 are pixelHinting, noScale, capsStyle, jointStyle, and miterLimit.

The following procedure demonstrates the difference between the three new caps styles in Flash Player 8: none, round, and square.

To set caps styles using ActionScript:

  1. Create a new Flash document and save it as capstyle.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    // Set up grid movie clip.

    this.createEmptyMovieClip("grid_mc", 50);

    grid_mc.lineStyle(0, 0x999999, 100);

    grid_mc.moveTo(50, 0);

    grid_mc.lineTo(50, Stage.height);

    grid_mc.moveTo(250, 0);

    grid_mc.lineTo(250, Stage.height);

    // line 1 (capsStyle: round)

    this.createEmptyMovieClip("line1_mc", 10);

    with (line1_mc) {

    createTextField("label_txt", 1, 5, 10, 100, 20);

    label_txt.text = "round";

    lineStyle(20, 0x99FF00, 100, true, "none", "round", "miter", 0.8);

    moveTo(0, 0);

    lineTo(200, 0);

    _x = 50;

    _y = 50;

    }

    // line 2 (capsStyle: square)

    this.createEmptyMovieClip("line2_mc", 20);

    with (line2_mc) {

    createTextField("label_txt", 1, 5, 10, 100, 20);

    label_txt.text = "square";

    lineStyle(20, 0x99FF00, 100, true, "none", "square", "miter", 0.8);

    moveTo(0, 0);

    lineTo(200, 0);

    _x = 50;

    _y = 150;

    }

    // line 3 (capsStyle: none)

    this.createEmptyMovieClip("line3_mc", 30);

    with (line3_mc) {

    createTextField("label_txt", 1, 5, 10, 100, 20);

    label_txt.text = "none";

    lineStyle(20, 0x99FF00, 100, true, "none", "none", "miter", 0.8);

    moveTo(0, 0);

    lineTo(200, 0);

    _x = 50;

    _y = 250;

    }

    The preceding code dynamically creates four movie clips and uses the Drawing API to create a series of lines on the Stage. The first movie clip contains two vertical lines, one at 50 pixels and the other at 250 pixels on the x-axis. The next three movie clips each draw a green line on the Stage and sets their capsStyle to round, square, or none.

  3. Select Control > Test Movie to test the document.

The different caps styles appear on the Stage at runtime.
 

Setting parameters of line styles

TOP

You can set the parameters of line styles to change the appearance of your strokes. You can use parameters to change the thickness, color, alpha, scale, and other attributes of the line style.

Setting line thickness

The thickness parameter of the MovieClip.lineStyle() method lets you specify the thickness of the line drawn in points as a number. You can draw a line any thickness between 0 and 255 points wide, although setting the thickness to 0 creates what is called a hairline thickness, where the stroke is always 1 pixel, regardless of whether the SWF file is zoomed in or resized.
The following procedure demonstrates the difference between a standard 1-pixel thickness line and a hairline thickness line.

To create a hairline stroke:

  1. Create a new Flash document and save it as hairline.fla.

  2. Add the following ActionScript to Frame 1 of your Timeline:

    this.createEmptyMovieClip("drawing_mc", 10);

    // create a red, hairline thickness line

    drawing_mc.lineStyle(0, 0xFF0000, 100);

    drawing_mc.moveTo(0, 0);

    drawing_mc.lineTo(200, 0);

    drawing_mc.lineTo(200, 100);

    // create a blue line with a 1 pixel thickness

    drawing_mc.lineStyle(1, 0x0000FF, 100);

    drawing_mc.lineTo(0, 100);

    drawing_mc.lineTo(0, 0);

    drawing_mc._x = 100;

    drawing_mc._y = 100;

    The preceding code uses the Drawing API to draw two lines on the Stage. The first line is red and has a thickness of 0, indicating a hairline thickness, the second line is blue and has a thickness of 1 pixel.

  3. Save the Flash document and select Control > Test Movie to test the SWF file.

Initially, both the red and blue lines look exactly the same. If you right-click in the SWF file and select Zoom In from the context menu, the red line always appears as a 1-pixel line; however, the blue line grows larger each time you zoom in to the SWF file.

Setting line color (rgb)

The second parameter in the lineStyle() method, rgb, lets you control the color of the current line segment as a number. By default, Flash draws black lines (#000000), although you can specify different colors by setting a new hexidecimal color value using 0xRRGGBB syntax. In this syntax, RR is a red value (between 00 and FF), GG is a green value (00 to FF), and BB is a blue value (00 to FF).

For example, you represent a red line as 0xFF0000, a green line as 0x00FF00, a blue line as 0x0000FF, a purple line as 0xFF00FF (red and blue), a white line as #FFFFFF, a gray line as #999999, and so on.

Setting line alpha

The third parameter in the lineStyle() method, alpha, lets you control the transparency (alpha) level for the line. Transparency is a numerical value between 0 and 100, where 0 represents a completely transparent line, and 100 is completely opaque (visible).

Setting line pixel hinting (pixelHinting)

The pixel hinting for strokes parameter, pixelHinting, means that line and curve anchors are set on full pixels. The strokes are on full pixels for any stroke thickness, which means that you never see a blurry vertical or horizontal line. You set the pixelHinting parameter to a Boolean value (true or false).

Setting line scale (noScale)

You set the noScale parameter by using a String value, which lets you specify a scaling mode for the line. You can use a nonscaleable stroke in horizontal mode or vertical mode, scale the line (normal), or use no scaling.

TIP : It is useful to enable scaling for user interface elements when users zoom in, but not if a movie clip is only scaled vertically or horizontally.

You can use one of four different modes to specify when scaling should occur and when it shouldn't. The following are the possible values for the noScale property:

normal  Always scale the thickness (default).

vertical Do not scale the thickness if the object is scaled vertically.

horizontal Do not scale the thickness if the object is scaled horizontally.

none Never scale the thickness.

Setting line caps (capsStyle) and joints (jointStyle)

You can set three types of caps styles for the capsStyle parameter:

  • round (default)

  • square

  • none

The following procedure demonstrates the differences between each of the three caps styles. A visual representation of each cap style appears on the Stage when you test the SWF file.

To set different caps styles:

  1. Create a new Flash document and save it as capsstyle2.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    var lineLength:Number = 100;

    // round

    this.createEmptyMovieClip("round_mc", 10);

    round_mc.lineStyle(20, 0xFF0000, 100, true, "none", "round");

    round_mc.moveTo(0, 0);

    round_mc.lineTo(lineLength, 0);

    round_mc.lineStyle(0, 0x000000);

    round_mc.moveTo(0, 0);

    round_mc.lineTo(lineLength, 0);

    round_mc._x = 50;

    round_mc._y = 50;

    var lbl:TextField = round_mc.createTextField("label_txt", 10, 0, 10, lineLength, 20);

    lbl.text = "round";

    var lineLength:Number = 100;

    // square

    this.createEmptyMovieClip("square_mc", 20);

    square_mc.lineStyle(20, 0xFF0000, 100, true, "none", "square");

    square_mc.moveTo(0, 0);

    square_mc.lineTo(lineLength, 0);

    square_mc.lineStyle(0, 0x000000);

    square_mc.moveTo(0, 0);

    square_mc.lineTo(lineLength, 0);

    square_mc._x = 200;

    square_mc._y = 50;

    var lbl:TextField = square_mc.createTextField("label_txt", 10, 0, 10, lineLength, 20);

    lbl.text = "square";

    // none

    this.createEmptyMovieClip("none_mc", 30);

    none_mc.lineStyle(20, 0xFF0000, 100, true, "none", "none");

    none_mc.moveTo(0, 0);

    none_mc.lineTo(lineLength, 0);

    none_mc.lineStyle(0, 0x000000);

    none_mc.moveTo(0, 0);

    none_mc.lineTo(lineLength, 0);

    none_mc._x = 350;

    none_mc._y = 50;

    var lbl:TextField = none_mc.createTextField("label_txt", 10, 0, 10, lineLength, 20);

    lbl.text = "none";

    The preceding code uses the Drawing API to draw three lines, each with a different value for capsStyle.

  3. Select Control > Test Movie to test the Flash document.

You can set the following three types of joint styles for the jointStyle parameter:

  • round (default)

  • miter

  • bevel

The following example demonstrates the differences between each of the three joint styles.

To set different joint styles:

  1. Create a new Flash document and save it as jointstyles.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    var lineLength:Number = 100;

    // miter

    this.createEmptyMovieClip("miter_mc", 10);

    miter_mc.lineStyle(25, 0xFF0000, 100, true, "none", "none", "miter", 25);

    miter_mc.moveTo(0, lineLength);

    miter_mc.lineTo(lineLength / 2, 0);

    miter_mc.lineTo(lineLength, lineLength);

    miter_mc.lineTo(0, lineLength);

    miter_mc._x = 50;

    miter_mc._y = 50;

    var lbl:TextField = miter_mc.createTextField("label_txt", 10, 0, lineLength + 20, lineLength, 20);

    lbl.autoSize = "center";

    lbl.text = "miter";

    // round

    this.createEmptyMovieClip("round_mc", 20);

    round_mc.lineStyle(25, 0xFF0000, 100, true, "none", "none", "round");

    round_mc.moveTo(0, lineLength);

    round_mc.lineTo(lineLength / 2, 0);

    round_mc.lineTo(lineLength, lineLength);

    round_mc.lineTo(0, lineLength);

    round_mc._x = 200;

    round_mc._y = 50;

    var lbl:TextField = round_mc.createTextField("label_txt", 10, 0, lineLength + 20, lineLength, 20);

    lbl.autoSize = "center";

    lbl.text = "round";

    // bevel

    this.createEmptyMovieClip("bevel_mc", 30);

    bevel_mc.lineStyle(25, 0xFF0000, 100, true, "none", "none", "bevel");

    bevel_mc.moveTo(0, lineLength);

    bevel_mc.lineTo(lineLength / 2, 0);

    bevel_mc.lineTo(lineLength, lineLength);

    bevel_mc.lineTo(0, lineLength);

    bevel_mc._x = 350;

    bevel_mc._y = 50;

    var lbl:TextField = bevel_mc.createTextField("label_txt", 10, 0, lineLength + 20, lineLength, 20);

    lbl.autoSize = "center";

    lbl.text = "bevel";

    Flash uses the Drawing API to draw three triangles on the Stage. Each triangle has a different value for its joint style.

  3. Save the Flash document and select Control > Test Movie to test the document.

Setting line miter (miterLimit)

The miterLimit property is a numerical value that indicates the limit at which a miter joint (see Setting line caps (capsStyle) and joints (jointStyle)) is cut off. The miterLimit value is a general multiplier of a stroke. For example, with a value of 2.5, miterLimit is cut off at 2.5 times the stroke size. Valid values range from 0 to 255 (if a value for miterLimit is undefined, the default value is 3). The miterLimit property is only used if jointStyle is set to miter.
 

Using Drawing API methods and scripting animation

TOP

You can combine the Drawing API with the Tween and TransitionManager classes to create some excellent animated results, and you only have to write a small amount of ActionScript.
The following procedure loads a JPEG image and dynamically masks the image so you can reveal the image slowly after it loads by tweening the image's mask.

To animate dynamic masks:

  1. Create a new Flash document and save it as dynmask.fla.

  2. Add the following ActionScript to Frame 1 of the Timeline:

    import mx.transitions.Tween;

    import mx.transitions.easing.*;

    var mclListener:Object = new Object();

    mclListener.onLoadInit = function(target_mc:MovieClip) {

    target_mc._visible = false;

    // Center the image on the Stage.

    target_mc._x = (Stage.width - target_mc._width) / 2;

    target_mc._y = (Stage.height - target_mc._height) / 2;

    var maskClip:MovieClip = target_mc.createEmptyMovieClip("mask_mc", 20);

    with (maskClip) {

    // Draw a mask that is the same size as the loaded image.

    beginFill(0xFF00FF, 100);

    moveTo(0, 0);

    lineTo(target_mc._width, 0);

    lineTo(target_mc._width, target_mc._height);

    lineTo(0, target_mc._height);

    lineTo(0, 0);

    endFill();

    }

    target_mc.setMask(maskClip);

    target_mc._visible = true;

    var mask_tween:Object = new Tween(maskClip, "_yscale", Strong.easeOut, 0, 100, 2, true);

    };

    this.createEmptyMovieClip("img_mc", 10);

    var img_mcl:MovieClipLoader = new MovieClipLoader();

    img_mcl.addListener(mclListener);

    img_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img_mc);

    This code example imports the Tween class and each of the classes in the easing package. Next, it creates an object that acts as the listener object for a MovieClipLoader instance that's created in a later section of the code. The listener object defines a single event listener, onLoadInit, which centers the dynamically loaded JPEG image on the Stage. After the code repositions the image, a new movie clip instance is created within the target_mc movie clip (which contains the dynamically loaded JPEG image). The Drawing API code draws a rectangle with the same dimensions as the JPEG image within this new movie clip. The new movie clip masks the JPEG image by calling the MovieClip.setMask() method. After the mask is drawn and set up, the mask uses the Tween class to animate, which causes the image to slowly reveal itself.

  3. Save the Flash document and select Control > Test Movie to test the SWF file.

NOTE : To animate _alpha in the previous example instead of _yscale, tween the target_mc directly instead of the mask movie clip.

 

Understanding scaling and slice guides

TOP

You can use 9-slice scaling (Scale-9) to specify component-style scaling for movie clips. 9-slice scaling lets you create movie clip symbols that scale appropriately for use as user interface components, as opposed to the type of scaling typically applied to graphics and design elements.

Understanding how 9-slice scaling works

The easiest way to explain how 9-slice scaling works is to look at an example of how 9-slice scaling works in Flash.

To understand scaling in Flash:

  1. Create a new Flash document and save it as dynmask.fla.

  2. Drag a copy of the Button component to the Stage from the Components panel (Window > Components).

     

  3. Increase the Stage's zoom level to 400% by using the Zoom tool.

    By default, the Button component instance is 100 pixels wide by 22 pixels high.

  4. Resize the Button component instance to 200 pixels width by 44 pixels high by using the Property inspector.

You can see that even though the component resized, the Button's border and text label do not distort. The button's label remained centered and maintained its font size. Although components of version 2 of the Macromedia Component Architecture do not use 9-slice scaling, components handle scaling in the version 2 component architecture so the outlines do not change size (as shown in the next figure).

Imagine that the button instance is sliced into 9 separate pieces, or a 3 by 3 grid, similar to a keypad on a telephone or keyboard. When you resize the button instance horizontally, only the three vertical segments in the center (numbers 2, 5, and 8 on a keypad) stretch so your content doesn't appear distorted. If you resized the button instance vertically, only the three horizontal segments in the center (numbers 4, 5, and 6 on a keypad) would resize. The four corners of the scaling grid are not scaled at all, which allows the component to grow without looking like it is being stretched (see the following images).

TIP : Strokes are created from the edges after the 9-slice scaling transformation, and therefore don't deform or lose detail.

You can enable slice guides for 9-slice scaling in the Flash environment within the Convert to Symbol dialog box or the Symbol Properties dialog box. The Enable guides for 9-slice scaling check box is available only if you are publishing for Flash Player 8 and the behavior is set to movie clip. The 9-slice scaling guides are not available for earlier versions of Flash or if you are creating a button or graphic symbol. 9-slice scaling can be enabled in ActionScript by setting the scale9Grid property on a movie clip instance.

Whether you created your slice guides by using the user interface or by using ActionScript, you can trace the x coordinate, y coordinate, width, and height by tracing the movie clip's scale9Grid property.

trace(my_mc.scale9Grid); // (x=20, y=20, w=120, h=120)

This snippet of code traces the value of the Rectangle object being used by the scale9Grid property. The rectangle has a x and y coordinates of 20 pixels, a width of 120 pixels and a height of 120 pixels.
 

Working with 9-slice scaling in ActionScript

TOP

In the following example, you use the drawing tools to draw a 300 pixel by 300 pixel square which is resized by using 9-slice scaling. The square is split up into nine smaller squares, each one approximately 100 pixels wide by 100 pixels high. When you resize the square, each segment that isn't a corner expands to match the specified width and height.

To use 9-slice scaling with ActionScript:

  1. Create a new Flash document and save it as ninescale.fla.

  2. Drag a Button component into the current document's library.

  3. Select the Rectangle tool and draw a red square (300 pixels by 300 pixels) with a 15-pixel black stroke on the Stage.

  4. Select the Oval tool and draw a purple circle (50 pixels by 50 pixels) with a 2-pixel black stroke on the Stage.

  5. Select the purple circle and drag it into the upper-right corner of the red square created earlier.

  6. Select the Oval tool and draw a new circle that is approximately 200 pixels by 200 pixels and position it off of the Stage.

  7. Select the new circle on the Stage and drag it so that the circle's center-point is in the lower-left corner of the square.

  8. Click outside of the circle instance to deselect the circle.

  9. Double-click the circle again to select it and press backspace to delete the shape and remove a circular portion of the square.

  10. Using the mouse, select the entire red square and inner purple circle.

  11. Press F8 to convert the shape into a movie clip symbol.

  12. Give the movie clip on the Stage an instance name of my_mc.

  13. Add the following ActionScript to Frame 1 of the main Timeline:

    import mx.controls.Button;

    import flash.geom.Rectangle;

    var grid:Rectangle = new Rectangle(100, 100, 100, 100);

    var small_button:Button = this.createClassObject(Button, "small_button", 10, {label:"Small"});

    small_button.move(10, 10);

    small_button.addEventListener("click", smallHandler);

    function smallHandler(eventObj:Object):Void {

    my_mc._width = 100;

    my_mc._height = 100;

    }

    var large_button:Button = this.createClassObject(Button, "large_button", 20, {label:"Large"});

    large_button.move(120, 10);

    large_button.addEventListener("click", largeHandler);

    function largeHandler(eventObj:Object):Void {

    my_mc._width = 450;

    my_mc._height = 300;

    }

    var toggle_button:Button = this.createClassObject(Button, "toggle_button", 30, {label:"scale9Grid=OFF", toggle:true, selected:false});

    toggle_button.move(420, 10);

    toggle_button.setSize(120, 22);

    toggle_button.addEventListener("click", toggleListener);

    function toggleListener(eventObj:Object):Void {

    if (eventObj.target.selected) {

    eventObj.target.label = "scale9Grid=ON";

    my_mc.scale9Grid = grid;

    } else {

    eventObj.target.label = "scale9Grid=OFF";

    my_mc.scale9Grid = undefined;

    }

    }

    The preceding code is separated into five sections. The first section of code imports two classes: mx.controls.Button (the Button component class) and flash.geom.Rectangle. The second section of code creates a new Rectangle class instance and specifies x and y coordinates of 100 pixels as well as a width and height of 100 pixels. This rectangle instance is used to set up the 9-slice scaling grid for a movie clip shape created later on.

    Next, you create a new Button component instance and give it an instance name of small_button. Whenever you click this button, the movie clip that you created earlier resizes to 100 pixels wide by 100 pixels high. The fourth section of code dynamically creates a new Button instance named large_button which, when clicked, resizes the target movie clip to 450 pixels wide by 300 pixels high. The final section of code creates a new Button instance that the user can toggle on and off. When the button is in the on state, the 9-slice grid is applied. If the button is in the off state, the 9-slice grid is disabled.

  14. Save the Flash document and select Control > Test Movie to test the SWF file.

This code example adds and positions three Button component instances on the Stage and creates event listeners for each button. If you click the Large button with the 9-slice grid disabled, you can see that the image becomes distorted and looks stretched. Enable the 9-slice grid by clicking the toggle button and click the Large button again. With the 9-slice grid enabled, the circle in the upper-left corner should no longer appear distorted.
 

Copyright ADOBE - All Rights Reserved Worldwide

 

 

More Topics:

Working with Flash Documents

How to work in Flash WorkSpace

Working with Projects in Flash

Process to Build your First Application in Flash

Using Symbols, Instances and Library Assets in Flash

How to Build Video Player in Flash

How to Work with Color, Strokes and Fills in Flash

How to Create Document in Flash

What is Vector and Bitmap Graphics in Flash

How to Create a Banner in Flash, Part 1

How to Work with Text in Flash

How to Create a Banner in Flash, Part 2

How to Use Imported Artwork in Flash

How to Create a Banner in Flash, Part 3

How to Work with Graphic Objects in Flash

How to Work with Layers in Flash

How to Use Filters and Blends

Working with Graphics in Flash

What is Accessibility Features in Flash

How to Create Motion (Shape Tween & Motion Tween) in Flash

How to Create an Application in Flash

What is Masking in Flash

How to Work with Video in Flash

How to Use Layout Tools in Flash

What are Behaviors in Flash

How to Work with Sound in Flash

How to Create Symbols and Instances in Flash

What is ActionScript in Flash

How to Write ActionScript With Script Assist in Flash

How to Add Button Animation and Navigation in Flash

What is Data Integration in Flash

How to Work with Screens

How to Create a Presentation with Screens

What is Extending Flash

How to Create Multilanguage Text in Flash

How to Create Graphics: Draw in Flash

What is Flash Lite

Ways of Data Integration

How to Create Graphics: Create a Timeline Animation in Flash

Getting Started with Flash Lite in Flash

How to Publish Flash Documents

How to Create Graphics: Making Animations with Easing

Learning Flash Lite 1.X ActionScript in Flash

How to Export Flash Content and Images from Flash

How to Create Graphics: Applying Gradients in Flash

Process of Writing and Editing ActionScript 2.0 in Flash

How to Create Accessible Content in Flash

How to Create Graphics: Apply Graphic Filters and Blends

What is Data and Data Types in Flash

Process of Printing from SWF Files in Flash

Using ActionScript: How to Use Script Assist mode in Flash

Learn Syntax and Language Fundamentals in Flash

How to Create E-learning Content in Flash

Using ActionScript: How to Write Scripts in Flash

Working with Functions and Methods in Flash

Process of Using Templates in Flash

Using ActionScript: Process of Adding Interactivity in Flash

What are Classes in Flash

Control Tag Summary of XML to UI in Flash

Using ActionScript: How to Create a Form with Conditional Logic and Send Data in Flash

What is Inheritance in Flash

What is Data Integration: Overview

Using ActionScript: How to Work with Objects and Classes in Flash

Overview on Interfaces in Flash

What is Data Integration: Using XML for a Timesheet

How to Work with Text and Strings in Flash

How to use Handling Events in Flash

What is Data Integration: Using XUpdate to Update the Timesheet

Learning Animation, Filters and Drawings in Flash

How to Work with Movie Clips in Flash

How to Create Interaction with ActionScript in Flash

How to Work with Images, Sound, and Video in Flash

How to Work with External Data in Flash

What is Security in Flash

How to Debug Applications in Flash

List of Error Messages in Flash

Using Object-Oriented Programming with ActionScript 1.0 in Flash

How to Write Scripts for Earlier Versions of Flash Player in Flash

List of all Keyboard Keys and Key Code Values for using in Flash

Terminology

Introduction to Components in Flash

What are Components in Flash

How to Create an Application with Components

How to Work with Components in Flash

How to Handle Component Events in Flash

How to Customize Components in Flash

How to Create Components in Flash

What is Collection Properties in Flash