Accessibility

Flash Article

 

Flash graphic effects learning guide

Adobe

 

Editor: Jen deHaan

Flash Authoring QE
Adobe
Jen deHaan's blog
flashthusiast.com
webvideoblogger.com

Reviewer: Dan Carr

Dan Carr Design

Note: This learning guide introduces graphic effects in Flash and provides you with tools for developing your skills. The Flash product documentation is the source of many of these materials. Always consult Flash Help (available both in the product and in Flash LiveDocs) first when learning to use new features.

Adobe Flash CS3 provides a number of features for producing impressive graphic effects. These features, along with the improved workflow of Flash CS3, open up an endless list of effect and production possibilities.

Along with some of the new drawing features and video capabilities, these graphic effects make up a category of tools promoting expressiveness—the ability to enhance the look and feel of your project. Many of these expressiveness features—in particular, the drawing-related features—are available in both Flash Basic and Flash Professional. However, some of the specialized effects features are only available in the Flash CS3 Professional user interface—or in both Flash CS3 Basic and Flash CS3 Professional when you use ActionScript code.

Here's a summary of a few of these important features:

While these filters and blends effects exist only in the Flash CS3 Professional user interface, both Flash Basic and Flash Professional provide tools to draw and animate your content. Both versions contain enhanced drawing tools, functionality and improved text rendering. You can apply filters and blend effects in both Flash CS3 Basic and Flash CS3 Professional using ActionScript code.

Note: The ActionScript samples in this article are written in ActionScript 3.0 and must be used within an ActionScript 3.0 file. See the Flash 8 version of this article for samples that can be used in an ActionScript 1.0 or 2.0 file.

Requirements

To follow along with this learning guide, you will need to install the following software:

Flash CS3 Professional

Prerequisite knowledge

This article assumes you are familiar with the Flash workspace and have a basic knowledge of working with Flash files. An intermediate knowledge of ActionScript is required for the sections of this learning guide that discuss how to create graphic effects programmatically.

Using Flash filters

Filters let you add interesting visual effects to text, buttons, and movie clips. Filters are most often associated with applying drop shadows, blurs, glows, and bevels to graphic elements. A feature unique to Flash is that you can animate the filters you apply using motion tweens. For example, if you create a ball (or sphere) with a drop shadow, you can simulate the look of the light source moving from one side of the object to another by changing the position of the drop shadow from its beginning and ending frames in the Timeline.

After you apply a filter, you can change its options at any time or rearrange the order of filters to experiment with combined effects. You can enable or disable filters or delete them in the Property inspector. When you remove a filter, the object returns to its previous appearance. You can view the filters applied to an object by selecting it; doing so automatically updates the filters list in the Property inspector for the selected object.

Applying filters

You can apply one or more filters to selected objects using the Property inspector. Each time you add a new filter to an object, it is added to the list of applied filters for that object in the Property inspector. You can apply multiple filters to an object, as well as remove filters that have been previously applied. Applying different filters affects the appearance of a movie clip instance (see Figure 1).

Examples of filter effects

Figure 1.Various examples of filter effects applied to movie clip instances

(+) View larger

For information on how using filters can affect the performance of your SWF files, see the following sections of Flash LiveDocs: About Filters and Flash Player Performance (Using Flash > Using Filters and Blends > About Filters and Flash Player Performance); and About Error Handling, Performance, and Filters (Learning ActionScript 2.0 in Flash > Animation, Filters, and Drawings > Using Filter Effects > About Error Handling, Performance, and Filters).

To apply a filter:
  1. Select a movie clip, button, or text object on the Stage to which you want to apply a filter. You can apply filters only to text, button, and movie clip objects.
  2. Select the Filter tab in the Property inspector.
  3. Click the Add Filter (+) button and select a filter from the Filters pop-up menu (see Figure 2). The filter you select is applied to the object and the controls for the filter settings appear in the Property inspector.

    Add Filter menu in the Property inspector


    Figure 2. Adding a filter to the Filter tab in the Property inspector

  4. Experiment with the filter settings until you get the look you want. For details about the settings available for each filter, see the following sections in Flash LiveDocs:

To remove a filter:
  1. Select the movie clip, button, or text object that you want to remove a filter from.
  2. Select the Filter tab in the Property inspector.
  3. Select the filter you want to remove in the list of applied filters.
  4. Click the Remove Filter (–) button to remove the filter.

You can create a filter settings library that allows you to easily apply the same filter or sets of filters to an object. Flash stores the filter presets you create in the Property inspector on the Filters tab in the Filters > Presets menu. You can delete or rename any presets as desired.

You can also share libraries of preset filters with other developers by providing them with the filter configuration file stored in your Flash Configuration folder.

For more information, see the following section of Flash LiveDocs: Using Flash > Special effects > About filters > Creating preset filter libraries.

To enable or disable a filter applied to an object:

Note: Alt-click the enable icon in the Filter list to toggle the enable state of the other filters in the list. If you Alt-click the disable icon, the selected filter is enabled and all other filters in the list are disabled.

To enable or disable all filters applied to an object:

Note: You can Control-click the enable or disable icon in the Filter list to enable or disable all the filters in the list.

At this point, you may want to try applying a basic filter effect yourself. There are many examples (see above) in the Flash documentation. However, an easy example to start with is applying a drop shadow, so try it out by using the following steps.

To apply a preset filter to an object:
  1. Select the movie clip, button, or text object that you want to apply a filter preset to.
  2. Select the Filter tab in the Property inspector.
  3. Click the Add Filter (+) button and select Presets from the Filters pop-up menu.
  4. Select the filter preset you want to apply from the list of available presets at the bottom of the preset menu.

Note: When you apply a filter preset to an object, Flash replaces any filters currently applied to the selected object(s) with the filter(s) used in the preset.

Creating a skewed drop shadow

Use the Drop Shadow filter's Hide object option to create a more realistic look by skewing the shadow of an object (see Figure 3). To achieve this effect, you need to create a duplicate movie clip, button, or text object, apply a drop shadow to the duplicate, and use the Free Transform tool to skew the duplicate object's shadow.

Skewing the Drop Shadow filter to create a more realistic-looking shadow

Figure 3. Skewing the Drop Shadow filter to create a more realistic shadow

To create a skewed drop shadow:
  1. Select the movie clip or text object whose shadow you want to skew.
  2. Duplicate (select Edit > Duplicate) the source movie clip or text object.
  3. Select the duplicated object, and skew it using the Free Transform tool (Modify > Transform > Rotate and Skew).
  4. Apply the Drop Shadow filter to the duplicated movie clip or text object, and select the Hide Object check box. The duplicated object is hidden from view, leaving only the skewed shadow.
  5. Adjust the Drop Shadow filter settings and the angle of the skewed drop shadow until you achieve the look you want.

Applying filters with ActionScript

You can apply filters using the Flash user interface in Flash CS3 Professional, or using ActionScript in Flash CS3 Basic or Flash CS3 Professional. You can apply each filter effect or group of effects to movie clips, buttons, or text fields using ActionScript.

If you use ActionScript to apply the filters to an instance, you can also use a displacement map filter or a convolution filter, which are not available in the Flash user interface. Filters are applied to the vector definitions, so there is no file size overhead of storing a bitmap image within the SWF file. You can also write ActionScript that allows you to modify an existing filter that you applied to a text field, movie clip, or button for dynamic effects.

Let's try applying a basic filter effect using ActionScript code. There are many examples in the Flash documentation (see the following list); however, an easy example to get started with involves applying a bevel filter. In the steps below, we've included a code example.

To apply a bevel filter:
  1. Create a new Flash document called bevel.fla.
  2. Create a new movie clip that contains a graphic or image, and give it the instance name my_mc.
  3. Select Frame 1 of the Timeline, and add the following ActionScript:
    import flash.filters.BevelFilter;
              
    // define a bevel filter
    var bevel:BevelFilter = new BevelFilter(4, 45, 0x99CCFF, 1, 0x003399, 1, 10, 10, 2, 3);
    
    // set strength
    bevel.strength = 5;
    
    // apply the filter to my_mc
    my_mc.filters = [bevel];
    
    

    Note: For information on working with ActionScript packages, such as flash.filters.BevelFilter, see the following section of Flash LiveDocs: Programming ActionScript 3.0 > ActionScript language and syntax > Packages and namespaces > Packages.

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

For information on the parameters you can pass to the bevel filter, see the following section of Flash LiveDocs: ActionScript 3.0 Language and Components Reference > All Classes > BevelFilter class (flash.filters.BevelFilter).

Applying different filters with code works pretty much the same way. However, different filters need different information when you apply the filter. For example, the color matrix filter requires an array. You can use the color matrix filter to modify the brightness of an instance, as the following example demonstrates.

To apply a color matrix filter:
  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.display.*;
    import flash.net.URLRequest;
    import flash.events.Event;
    import flash.filters.ColorMatrixFilter;
    
    var pictLdr:Loader = new Loader();
    var pictURL:String = "http://www.helpexamples.com/flash/images/image2.jpg";
    var pictURLReq:URLRequest = new URLRequest(pictURL);
    pictLdr.load(pictURLReq);
    pictLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded);
    addChild(pictLdr);
    
    function imgLoaded(event:Event):void
    {
        var myElements_array:Array = [1, 0, 0, 0, 10
        0, 1, 0, 0, 100,
        0, 0, 1, 0, 100,
        0, 0, 0, 1, 0];
        var myColorMatrix_filter:ColorMatrixFilter = new ColorMatrixFilter(myElements_array);
      pictLdr.content.filters = [myColorMatrix_filter];
    }
    
    

    This code dynamically loads a JPEG image using a MovieClipLoader instance. After the image has completely loaded and has been placed on the Stage, the instance's brightness is altered by using a color matrix filter.

    Note: The code sample above is written in ActionScript 3.0 and must be used within an ActionScript 3.0 file (the default Flash CS3 setting).

    For more information on the color matrix, see the following section of Flash LiveDocs: ActionScript 3.0 Language and Component Reference > All Classes > ColorMatrixFilter (flash.filters.ColorMatrixFilter).

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

    After you apply a filter, you can manipulate it using ActionScript, such as adjusting the filter properties or animating the filter. For more information, see the following sections: Adjusting Filter Properties with ActionScript and Animating Filters with ActionScript.

    Note: There are two additional filters that you can apply using ActionScript code, but they are not available using the Flash user interface: the convolution filter and the displacement map filter. For information on these filters see the following section of Flash LiveDocs:

    • For more information on the Convolution filter, see the ConvolutionFilter class (ActionScript 3.0 Language and Components Reference > All Classes > ConvolutionFilter class)
    • For more information on the Displacement Map filter, see the DisplacementMapFilter class (ActionScript 3.0 Language and Components Reference > All Classes > DisplacementMapFilter class)

See the following sections of Flash LiveDocs for examples of applying each filter using ActionScript code:

Applying multiple filters with ActionScript

You access the array of filters applied to an object through standard ActionScript calls using the DisplayObject.filters property. This returns an array that contains each filter object currently associated with the movie clip. By adding more than one filter to an objects filters array, you can apply multiple effects. The effects will be applied in the order they are listed in the array.

It's important to note that setting the filters property duplicates the filters array that you pass into it (demonstrated in the following example) and does not store the filter 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 will not work:

// This will not work
my_mc.filters[0].push(myFilter);

Because the previous code snippet returns a copy of the filters array, it modifies the duplicate. The following code example adds a blur filter to the end of an object's existing filter list:

// This will work:
import flash.filters.BlurFilter;
var filterList:Array = myClip.filters;
filterList.push(new BlurFilter(3,3,2));
myClip.filters = filterList;

The advantage of this is that you can copy the filters from one object, modify them and apply them to another object without worrying about affecting the original object's filters.

Adjusting filter properties with ActionScript

The array of filters applied to an object can be accessed through standard ActionScript calls using the MovieClip.filters property. By adding more than one filter to an object's filters array you can apply multiple effects. The filters will be applied in the order they are listed in the array. This returns an array that contains each filter object currently associated with the movie clip. Each filter has a set of properties unique to it. The filters can be accessed and modified just like a regular array object, although getting and setting the filters using the filters property returns a duplicate of the filters object instead of a reference.

Setting the filters property duplicates the filters array that you pass into it (demonstrated in the following example) and does not store the filter as a reference. When getting the filters property, it returns a new copy of the array. This allows you to copy the filters from one object, modify them, and apply them to another object without worrying about affecting the original object's filters. One negative implication of this approach is that the following code will not work:

// This will not work
my_mc.filters[0].blurX = 20;

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

// This will work
var filterList:Array = my_mc.filters;
filterList[0].blurX = 20;
my_mc.filters = filterList;

The following example blurs an image based on the current position of the mouse pointer on the Stage. Whenever the mouse cursor 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.display.*;
    import flash.net.URLRequest;
    import flash.events.Event;import flash.filters.BlurFilter;
    var pictLdr:Loader = new Loader();
    var pictURL:String = "http://www.helpexamples.com/flash/images/image2.jpg";
    var pictURLReq:URLRequest = new URLRequest(pictURL);
    pictLdr.load(pictURLReq);
    pictLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded); 
    addChild(pictLdr);
    
    function imgLoaded(event:Event):void{
       pictLdr.filters = [new BlurFilter(10, 10, 2)];
       pictLdr.x = (stage.stageWidth - pictLdr.width) / 2;
       pictLdr.y = (stage.stageHeight - pictLdr.height) / 2;
       pictLdr.addEventListener(MouseEvent.MOUSE_MOVE, redrawEffect);
    } 
    		  
    function redrawEffect(event:MouseEvent):void{
       var tempFilter:BlurFilter = pictLdr.filters[0];
       tempFilter.blurX = Math.floor((event.stageX / stage.stageWidth) * 100);
       tempFilter.blurY = Math.floor((event.stageY / stage.stageHeight) * 100);
       pictLdr.filters = [tempFilter];}

    Note: The code sample above is written in ActionScript 3.0 and must be used within an ActionScript 3.0 file (the default Flash CS3 setting).

  3. The previous code example is split into three sections. The first section imports the flash.filters.BlurFilter class and other necessary packages so that you don't have to use the fully qualified class name when you refer to each class. The second section loads an image and assigns it to a display object with its initial settings. The third section of code responds to the mouse movement on the Stage and adjusts the blur accordingly.
  4. Select Control > Test Movie to test the Flash document. When you move the mouse cursor horizontally along the x-axis it modifies the blur filter's blurX property. Moving the mouse cursor vertically along the y-axis modifies the blur filter's blurY property. The closer the mouse cursor is to the upper left corner of the Stage, the less blurring will be applied to the movie clip.

Animating filters

You can animate movie clips that have filters applied to them. Objects on separate keyframes that are joined by a tween have their parameters for corresponding filters tweened on intermediate frames. If a filter does not have a matching filter (a filter of the same type) at the opposite end of the tween, a matching filter is added automatically to ensure that the effect comes at the end of the animation sequence.

To animate a filter using the Flash user interface:
  1. Create a new Flash document and save it as anifilter.fla.
  2. Create or add a movie clip instance on the Stage at Frame 1.
  3. Select the instance and open the Filters tab.
  4. Click the Add Filter (+) button and select Glow from the pop-up menu.
  5. In the Filters tab, change the Blur X and Blur Y values to 25.
  6. Select Frame 15 on the Timeline and press F6 to insert a new keyframe.
  7. Select the movie clip instance again and open the Filters tab.
  8. Change the Blur X and Blur Y values to 2.
  9. Right-click (Windows) or Control-click (Macintosh) and select Create Motion Tween from the context menu.
  10. Select Control > Test Movie to test the animated filter.

Note: Flash CS3 Professional supports advanced control over tweening with the custom easing control panel. With the tween selected, click on the Edit button in the Properties inspector to access the easing controls.

Flash prevents motion tweens from functioning incorrectly in the event of a missing filter at one end of the tween, or filters applied in a different order at each end. For example, if you create a motion tween using the Drop Shadow filter and apply a drop shadow with a knockout on the first frame of the tween and an inner shadow on the last frame of the tween, Flash corrects the inconsistent use of the filter in the motion tween. In this case, Flash applies the filter settings used on the first frame of the tween—a drop shadow with a knockout.

For more information on how Flash prevents animations from functioning incorrectly, see the following section of Flash LiveDocs: Using Flash > Special effects > About filters > About Animating Filters.

Animating filters with ActionScript

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

In the first example, you apply a Glow filter to a movie clip instance. Using an enterFrame event handler, you animate the amount of glow that's applied to the movie clip.

To animate a filter using code:
  1. Create a new Flash document and save it as animFilter.fla.
  2. Draw a graphic on the Stage, select it, and then select Modify > Convert to Symbol.
  3. Name the movie clip symbol and then click OK.
  4. Select the movie clip instance on the Stage and then type my_mc in the Instance Name text box in the Property inspector.
  5. Add the following ActionScript to Frame 1 of the Timeline:
    import flash.filters.GlowFilter;
    var dir:Number = 1;
    my_mc.blur = 10;
    my_mc.filters = [new GlowFilter()];
    my_mc.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
    
    function enterFrameHandler(event:Event):void
    {   
    	my_mc.blur += dir;
    
    	if ((my_mc.blur >= 30) || (my_mc.blur <= 10)) {
    		dir *= -1;
    	}
    
    	var filter_array:Array = my_mc.filters;
    	filter_array[0].blurX = my_mc.blur;
    	filter_array[0].blurY = my_mc.blur;
    	my_mc.filters = filter_array;
    }

    Note: The code sample above is written in ActionScript 3.0 and must be used within an ActionScript 3.0 file (the default Flash CS3 setting).

    This code applies a glow filter to your movie clip instance on the Stage and defines an enterFrame event handler, which is responsible for animating the filter effect. The enterFrame event handler animates the glow filter between a blur of 10 and 30 pixels. After the animation is greater than or equal to 30, or less than or equal to 10, the direction of the animation reverses.

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

Filters and Flash Player performance

Here's an important thing to remember as you apply filters to movie clips in your Flash files: The type, number, and quality of filters you apply to objects can affect the performance of SWF files as you play them. The more filters you apply to an object, the greater the number of calculations Flash Player must process to display correctly the visual effects you've created. For this reason, Adobe recommends that you apply only a limited number of filters to a given object.

The actual impact at runtime is heavily dependent on the screen area that the filters are being applied to and how often the player has to redraw the filter. The player will automatically cache movie clips with filters applied as bitmaps to avoid having to redraw them each frame. When a movie clip is modified by rotating, resizing, or otherwise changing its appearance, the player redraws the clip and its effects. Note that translating (moving) a movie clip does not cause a redraw. For more information on bitmap caching, see the section on Runtime bitmap caching.

Each filter includes controls that let you adjust the strength and quality of the applied filter. Using lower settings improves performance on slower computers. If you are creating content for playback on a wide range on computers, or are unsure of the computing power available to your audience, set the quality level to low in order to maximize playback performance.

Tip: When applying a blur filter with ActionScript, using values for blurX and blurY which are powers of two (such as 2, 4, 8, 16, and 32) can be computed faster and offer the benefit of a 20–30% performance improvement.

Using blend modes

Blend modes let you create composite images. Compositing refers to the process of varying the transparency or color interaction of two or more overlapping objects. Blending allows you to create unique effects by blending the colors in overlapping movie clips, as well as adding a dimension of control to the opacity of objects and images. You can use Flash blending modes to create highlights or shadows that let details from an underlying image show through, or to colorize a desaturated image.

A blending mode contains these elements:

Blend modes in Flash

Because blend modes depend on both the color of the object to which you're applying the blend and the underlying color, you'll need to experiment with different colors to see what the result will be. Try experimenting with the different blend modes to achieve the effect you want.

Flash provides the following blend modes:

Note: The Erase and Alpha blend modes require that a blend mode other than Normal be applied to the parent movie clip.

Blend mode examples

Different blend modes affect the appearance of an image in different ways. Be aware that the resulting effect of a blend mode may be considerably different, depending on the color of the underlying image and type of blend mode you apply (see Figure 4).

Examples of blend modes

Figure 4. Examples of blend modes

(+) View larger

Applying a blend mode

You use the Property inspector to apply blend modes to selected movie clips.

To apply a blend mode to a movie clip:
  1. Select the movie clip instance (on the Stage) to which you want to apply a blend mode.
  2. Adjust the color and transparency of the movie clip instance using the Color pop-up menu in the Property inspector.
  3. Select a blend mode from the Blend pop-up menu in the Property inspector. The blend mode is applied to the selected movie clip instance.
  4. Verify that the blend mode you've selected is appropriate to the effect you're trying to achieve.

You might need to experiment with both the color and transparency settings of the movie clip and then try applying different blend modes to achieve the effect you want. For information on adjusting the color of a movie clip, see the following section of Flash LiveDocs: Using Flash > Using symbols, instances, and library assets > Working with symbol instances > Change the color and transparency of an instance.

Applying a blend mode using ActionScript

You can also apply blend modes to instances using ActionScript code in Flash CS3 Basic and Flash CS3 Professional. For example, you can apply the difference blend mode using the following code.

Type the following ActionScript on Frame 1 of the Timeline:

var pictLdr:Loader = new Loader();
var pictURL:String = "http://www.helpexamples.com/flash/images/image1.jpg";
var pictURLReq:URLRequest = new URLRequest(pictURL);
pictLdr.load(pictURLReq);
pictLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded); 
addChild(pictLdr);

function imgLoaded(event:Event):void
{
	pictLdr.blendMode = "difference";
}

Note: The code sample above is written in ActionScript 3.0 and must be used within an ActionScript 3.0 file (the default Flash CS3 setting).

Then select Control > Test Movie to test the document.

To see how different blend modes are applied to an image, follow along with the next example. The code below loads a dynamic image and allows you to apply different blending modes to the image by selecting a blending mode from a combo box on the Stage.

To apply blend modes to an image using ActionScript:
  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. Place the ComboBox instance somewhere along the top edge of the Stage.
  3. Add the following ActionScript to Frame 1 of the Timeline:
    import fl.data.DataProvider;
    import flash.display.*;
    import flash.net.URLRequest;
    import flash.events.Event;
    
    // Create a list of mode typesvar 
    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"});
    
    // Initialize the combobox
    blendMode_cb.dataProvider = new DataProvider(blendMode_dp);
    blendMode_cb.addEventListener(Event.CHANGE,changeHandler);
    
    // Create an event handler for the comboboxfunction 
    changeHandler(event:Event):void {   pictLdr.blendMode = event.target.selectedItem.data;}
    
    // Create a colored rectangle for the overlay
    var rect:Shape = new Shape();
    rect.graphics.beginFill(0xFF0000);
    rect.graphics.moveTo(100,100);
    rect.graphics.lineTo(350,100);
    rect.graphics.lineTo(350,350);
    rect.graphics.lineTo(100,350);
    rect.graphics.lineTo(100,100);
    addChild(rect);
    
    // Load an image to view the modesvar pictLdr:Loader = new Loader();
    var pictURL:String = "http://www.helpexamples.com/flash/images/image1.jpg";
    var pictURLReq:URLRequest = new URLRequest(pictURL);pictLdr.load(pictURLReq);
    pictLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded); 
    addChild(pictLdr);
    
    // Layout the image when it has downloadedfunction imgLoaded(event:Event):void
    {
        pictLdr.x = (stage.stageWidth - pictLdr.width) / 2;
        pictLdr.y = (stage.stageHeight - pictLdr.height) / 2;
    }
    
    

    Note: The code sample above is written in ActionScript 3.0 and must be used within an ActionScript 3.0 file (the default Flash CS3 setting).

    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 colored rectangle is drawn behind an image loaded from the server. The two images create a blending effect which displays differently each time a new blending mode is selected in the combo box.

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

Working with bitmaps

The BitmapData class lets you create arbitrarily sized transparent or opaque bitmap images and then manipulate them in various ways at runtime. By manipulating a BitmapData instance directly 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. The BitmapData class can be used for special effects on images, on demand video, and webcam video.

A BitmapData object contains an array of pixel data. This data can either represent a fully opaque bitmap or a transparent bitmap containing alpha channel data. Both types of BitmapData objects are stored as a buffer of 32-bit integers. Each 32-bit integer determines the properties of a single pixel in the bitmap. The 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.

Just as RGB colors are typically represented as six-digit hex numbers (for example, red is 0xFF0000), ARGB is represented as an eight-digit hex number, where the first two digits represent the alpha channel, the second two represent the red channel, and so on (for example, 50% opaque red would be represented as 0x80FF0000).

The following procedure dynamically loads a JPEG image onto the Stage and creates a noise effect, similar to static on a television, using the BitmapData class. The noise effect is redrawn with a random pattern every 100 milliseconds (1/10 of a second). Moving the mouse 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.Bitmap;
    import flash.display.BitmapData;
    
    // Load image
    var pictLdr:Loader = new Loader();
    var pictURL:String = "http://www.helpexamples.com/flash/images/image1.jpg";
    var pictURLReq:URLRequest = new URLRequest(pictURL);
    pictLdr.load(pictURLReq);
    pictLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded); 
    addChild(pictLdr);
    
    // Create bitmap data object
    var noiseBmd:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight, true);
    var noiseBm:Bitmap = new Bitmap(noiseBmd);addChild(noiseBm);
    
    // Initialize image when loaded
    function imgLoaded(event:Event):void
    {
       pictLdr.x = (stage.stageWidth - pictLdr.width) / 2;
       pictLdr.y = (stage.stageHeight - pictLdr.height) / 2;
       pictLdr.addEventListener(MouseEvent.MOUSE_MOVE, redrawEffect);}
    
    // Draw effect!function redrawEffect(event:MouseEvent):void
    {
       var low:Number = 30 * event.stageX / stage.stageWidth;
       var high:Number = 200 * event.stageY / stage.stageHeight;
       noiseBmd.noise(Math.round(Math.random() * 100000), low, high, 8, true);
    }
    
    

    Note: The code sample above is written in ActionScript 3.0 and must be used within an ActionScript 3.0 file (the default Flash CS3 setting).

    This code creates an image with an overlying bitmap data instance. When the mouse's position changes, the coordinates are used to calculate changes in the applied noise effect.

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

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

Runtime bitmap caching

As your designs in Flash grow in size, whether you are creating an application or complex scripted animation, you'll need to consider performance and optimization. When you have content that remains static (such as a rectangle movie clip), Flash does not optimize the content. Therefore, when you change the position of the rectangle movie clip, or when other elements change in its general vicinity, Flash redraws the entire rectangle in Flash Player 7 and earlier.

In Flash Player 8 or higher, you can cache specified movie clips and buttons to improve the performance of your SWF file. The movie clip or button is a surface, essentially a bitmap version of the instance's vector data, which is data that you do not intend to change much over the course of your SWF file. Since instances with caching turned on are not continually redrawn by Flash Player as the SWF file plays, the SWF file renders more quickly.

A cached bitmap is not created, even if you set it to cache, if one or more of the following occurs:

Applying bitmap caching is not always recommended, because in certain circumstances it can negatively affect SWF file performance. Bitmap caching also slightly increases RAM usage at runtime because the player must maintain both the vector data and cached bitmap in memory. For more information about when you should apply bitmap caching, see the following section of Flash LiveDocs: Programming ActionScript 3.0 > Display programming > Manipulating display objects > When to enable caching.

Note: You can update the vector data, and doing so causes the surface to be recreated. Therefore, it is not necessary for the cached vector data to remain the same for the entire SWF file.

To specify bitmap caching for a movie clip:
  1. Select the movie clip or button symbol on the Stage.
  2. In the Property inspector, select the Use runtime bitmap caching check box.

You can use ActionScript to enable caching or scrolling, as well as to control backgrounds. You can use the Property inspector to enable caching for a movie clip instance. If you do not want to use ActionScript, you can select the Use runtime bitmap caching option in the Property inspector instead.

If you use ActionScript, you can use three properties for button and display object instances. Using these properties, you can specify bitmap caching, set a background color for a display object (opaqueBackground), and set a property that allows your users to quickly scroll the movie clip content (scrollRect). To learn more, review a table containing detailed information in the following section of Flash LiveDocs: Programming ActionScript 3.0 > Display programming > Manipulating display objects > Panning and scrolling display objects.

To cache a display object instance, you need to set the cacheAsBitmap property to true. After you set the cacheAsBitmap property to true, you might notice that the instance automatically pixel-snaps to whole coordinates. When you test the SWF file, you should notice that complex vector animation renders much faster.

To cache a movie clip using ActionScript:
  1. Create a new Flash document, and name the file cachebitmap.fla.
  2. Create or import a complex vector graphic that covers the stage of the FLA file.
  3. Select the vector graphic and select Modify > Convert to Symbol.
  4. With the instance selected on the Stage, name it my_mc in the Property inspector.
  5. Select Frame 1 of the Timeline and then add the following ActionScript to the Actions panel:
    // Turn on bitmap caching for the large background
    my_mc.cacheAsBitmap = true;
  6. Select Control > Test Movie to test the document.

By caching the complex vector background graphic, the movie animates over the top of it without having to redraw the image during each frame of movement.

Note: You cannot apply caching directly to text fields. If you wish to apply caching to a text field, you can place a text field within a movie clip first, and then apply caching to the movie clip that contains the text field.

Working with text

Font rendering in Flash controls the way your text appears in a SWF file—that is, how it is rendered (or drawn) at runtime. Flash CS3 offers two types of anti-aliasing: normal and advanced. The advanced font rendering technology in Flash Player 8 and later helps make text appear legible and clear at small to regular font sizes, such as when you apply advanced anti-aliasing to your text fields. You can enable advanced anti-aliasing using either the Flash CS3 authoring tool or ActionScript. The improved capabilities mean that embedded text appears at the same level of quality as device text, and fonts appear the same on different platforms.

Anti-aliasing results in smooth text so that the edges of characters displayed onscreen look less jagged—which can be particularly helpful when you want to display text at small sizes. Anti-aliasing is supported for static, dynamic, and input text if the user has Flash Player 7 or later.

Note: When you open existing FLA files in Flash CS3, your text is not automatically updated to the Anti-Alias for Readability option; you must select individual text fields and manually change the anti-aliasing settings if you want to take advantage of the advanced anti-aliasing rendering technology.

Advanced and custom anti-alias features support the following:

Advanced and custom anti-alias features do not support the following:

Note: When text is animated, the player turns off advanced anti-aliasing to improve the appearance of your text while it's moving. After the animation is complete, anti-aliasing is turned back on. Subpixel rendering is also disabled for fields with advanced anti-aliasing when they are cached as bitmaps, have a filter applied to them, or are drawn into a BitmapData object.

There are five different font rendering options available in Flash CS3. To choose an option, select the text field and open the Property inspector. Select an option from the Font rendering method pop-up menu:

When you open a FLA file created for use with Flash Player 7 or earlier, the Property inspector sets the anti-alias option to its equivalent anti-aliasing option from Flash MX 2004 to the file's text. Text from older FLA files can be anything except for Anti-Alias for Readability and Custom Anti-Alias.

To use the Anti-alias for Readability or Custom Anti-Alias options with your text fields:
  1. Create a new Flash document.
  2. Select the Text tool and create new text fields on the Stage.
  3. Type inside the text field to create text.
  4. Select the text field to which you want to apply the Anti-Alias for Readability or Custom Anti-Alias option.
  5. In the Property inspector, select Anti-Alias for Readability or Custom Anti-Alias from the Font Rendering Method pop-up menu.

Tip: Advanced anti-aliasing is not recommended for very large fonts (larger than 48 points).

You can also apply Anti-alias for Readability or Custom Anti-alias using ActionScript, which is essential when you need more control over the appearance, content, and formatting of your text fields. Advanced anti-aliasing is available only in Flash Player 8 and later, and can be used only if you embed the font in the library and have the text field's embedFonts property set to true. For Flash Player 9, the default setting for text fields created using ActionScript is normal.

To set values for the TextField.antiAliasType property, use the following string values:

To apply advanced anti-aliasing using ActionScript:
  1. Create a new Flash document and save it as antialiastype.fla.
  2. Somewhere off the stage and out of view, create a new dynamic text field using the Text tool and set the font to Arial.
  3. With the text field selected, click on the Embed button in the Property inspector and embed the Arial font set into the text field. This step embeds the font and makes it available to the following code in Step 4.
  4. Add the following ActionScript to Frame 1 of the main Timeline:
    // Create the field's format
    var format:TextFormat = new TextFormat();
    format.color = 0x336699;
    format.size = 10;
    format.font = "Arial";
    
    // Create the text field
    var myText:TextField = new TextField();
    myText.embedFonts = true;
    myText.autoSize = TextFieldAutoSize.LEFT;
    myText.antiAliasType = AntiAliasType.ADVANCED;
    myText.defaultTextFormat = format;
    myText.selectable = false;
    myText.mouseEnabled = true;
    myText.text = "Hello World";addChild(myText);
    myText.addEventListener(MouseEvent.CLICK, clickHandler);
    
    // Toggle the antialias mode when the text is clicked on
    function clickHandler(event:Event):void
    {
       if( myText.antiAliasType == AntiAliasType.NORMAL ){
          myText.antiAliasType = AntiAliasType.ADVANCED;
       }else{
          myText.antiAliasType = AntiAliasType.NORMAL;
       }
    }
    
    

    Note: The code sample above is written in ActionScript 3.0 and must be used within an ActionScript 3.0 file (the default Flash CS3 setting).

    The previous code is split into four key areas. The first block of code creates a new TextFormat object, which specifies a font and font size to be used for a text field that will be created shortly.

    The second block of code creates a new text field with the instance name myText. In order for the font to be properly embedded, you must set embedFonts to true for the text field instance. The code also sets the text formatting for the new text field to the TextFormat object that you created earlier.

    The third, and final, block of code defines the click handler, which toggles the antiAliasType property between normal and advanced.

  5. Save your changes to the FLA file.
  6. Select Control > Test Movie to test your Flash document.
  7. Click the text field on the Stage.

Clicking the text field switches the anti-alias type from normal (the default) to advanced. When you are dealing with text fields with a smaller font size, setting the anti-aliasing to advanced can dramatically improve the readability of the text.

Tip: Advanced anti-aliasing allows font faces to be rendered at very high quality at small sizes. It is best used with applications that include a great deal of small text. Advanced anti-aliasing is not recommended for very large fonts (larger than 48 points).

For information on formatting anti-alias text, see the following sections of Flash LiveDocs: Programming ActionScript 3.0 > Working with text > Advanced Text Rendering.

New graphic effects features in Flash CS3 Professional

Among the many workflow improvements included with Flash CS3, there are a handful of new graphic effects features that provide new options for animation and graphic production.

This section provides an overview of the new copy and paste motion features as well as the enhanced 9-slice scaling feature.

Copy and paste motion

One exciting new feature is the ability to create a motion tween along the timeline and then copy and paste the exact tweening effect on another object. This feature can act as a consistency tool and offers an easy and efficient method for applying animation effects across a Flash movie or multiple Flash movies.

To copy and paste all the properties of a motion tween:
  1. Create a new FLA file and name it pasteMotion.fla.
  2. Name the default layer shape1. Draw a shape on frame 1 and convert it to a symbol (Modify > Convert to Symbol).
  3. Insert a second keyframe at frame 20 on the same layer.
  4. Change the physical properties of the instance at frame 20 and activate the tween by right-clicking (Alt-clicking on Mac) on the Timeline between the two keyframes. Choose the Create Motion Tween option from the context menu.
  5. Select the frames in the motion tween using the cursor and right-click (Alt-click on Mac) in the selection. Choose the Copy Motion option from the context menu.
  6. Create a new layer named shape2 and draw a second shape on the layer. Select the shape and convert it to a symbol.
  7. Insert a keyframe on frame 20 of the shape2 layer. Select both keyframes and right-click (Alt-click on Mac) in the selection.
  8. Choose the Paste Motion option to paste the motion tween to the shape2 layer.
  9. Export the SWF file (Control > Test Movie) to see the animations play.
To copy and paste specific properties of a motion tween:
  1. Repeat Steps 1–7 above.
  2. This time choose the Paste Motion Special option. The Paste Motion Special dialog appears (see Figure 5).

    Paste Motion Special dialog

    Figure 5. Paste Motion Special dialog box allowing you to select the properties you'd like to paste

  3. Select the options from the original tween that you want to paste and click the OK button to apply the effect.
  4. Export the SWF file (Control > Test Movie) to see the animations play.

Copy and paste motion as ActionScript 3.0

Copying a motion tween as ActionScript 3.0 allows you to paste the effect as ActionScript. The resulting ActionScript uses descriptive data written in XML format along with the ActionScript 3.0 Animator class to dynamically create the animation effect. This approach offers a quick way to generate animation in your code-based work or as a consistent way to quickly apply motion animation settings to a number of objects without using the Timeline.

To copy a motion tween as ActionScript 3.0:
  1. Create a new FLA file and name it pasteAS3Motion.fla
  2. Name the default layer shape1. Draw a shape on frame 1 and convert it to a symbol (Modify > Convert to Symbol).
  3. Insert a second keyframe at frame 20 on the same layer.
  4. Change the physical properties of the instance at frame 20 and activate the tween by right-clicking (Alt-clicking on Mac) on the timeline between the two keyframes. Choose the Create Motion Tween option from the context menu.
  5. Create a new layer named shape2 and draw a second shape on the layer. Select the shape and convert it to a symbol.
  6. With the new shape still selected, assign the instance name my_mc to the instance in the Property inspector.
  7. Select all the frames within the tween that you wish to copy and then right-click (Alt-click on Mac) again on the selection. Choose the Copy Motion as ActionScript 3.0 option from the context menu.
  8. In the prompt that appears, enter the instance name for the instance that the ActionScript-based animation should affect. In this case, enter my_mc. You can change the instance name later in the resulting code to target other movie clip instances. Click OK to accept the name. The motion tween is now saved as ActionScript in the Clipboard and can be pasted elsewhere.
  9. Create a third and final layer named actions. Select the first keyframe on the actions layer and paste the Clipboard contents into the frame:
    import fl.motion.Animator;
    var my_mc_xml:XML = <Motion duration="20" xmlns="fl.motion.*" xmlns:geom="flash.geom.*" xmlns:filters="flash.filters.*">
       <source>
          <Source frameRate="12" x="86.5" y="115.5" scaleX="1" scaleY="1" rotation="0" elementType="movie clip" symbolName="Symbol 1">
             <dimensions>
                <geom:Rectangle left="0" top="0" width="69" height="69"/>
             </dimensions>
             <transformationPoint>
                <geom:Point x="0.5" y="0.5"/>
             </transformationPoint>
          </Source>
       </source>
        <Keyframe index="0" tweenSnap="true" tweenSync="true">
          <tweens>
             <SimpleEase ease="0"/>
          </tweens>
       </Keyframe>
        <Keyframe index="19" x="391.95" y="58"/></Motion>;
     var my_mc_animator:Animator = new Animator(my_mc_xml, my_mc);my_mc_animator.play();
    
    
  10. Export the SWF file (Control > Test Movie) to see the animations play.

Note: When working with motion guides, some differences might occur between the XML that the Copy Motion command and the Copy Motion as ActionScript 3.0 command generate. If a motion guide and custom easing are applied to a tween, the Copy Motion XML tags include the properties of the Bezier curves for the easing, and the XML uses only two keyframes. For the same tween, using the Copy Motion as ActionScript 3.0 command creates keyframes for each frame, and applies the correct values to each keyframe. If you remove the motion guide, the same XML code appears describing the custom easing for both commands.

Tip: For dynamic processing of animations, explore using the Timeline object in Flash JavaScript (JSFL) for possibilities in author-time automation. In the Flash LiveDocs reference, see Extending Flash > Objects > Timeline object > timeline.copyMotionAsAS3().

9-slice scaling

The 9-slice scaling feature was introduced in Flash 8 and now features an improved, more accurate author-time preview in Flash CS3. This feature allows you to better control the effects of scaling vector graphics within movie clip instances. By using 9-slice scaling you can create graphics that can be scaled without the distortion that often occur in scaling. For example, you may find this feature very useful when creating button graphics with rounded corners where the graphic needs to change size while retaining the shape of the original button.

To turn on 9-slice scaling:
  1. Create a new FLA and name it scalingRectangle.fla.
  2. Using the Circle tool, draw nine circles of the same size (see Figure 6).
  3. Select all nine circles and convert them to a symbol (Modify > Convert to Symbol).
  4. In the symbol properties dialog, check the Enable guides for 9-slice scaling option.
  5. Click OK to accept the settings and then double-click on the instance to enter its symbol editing mode.
  6. Notice the guide lines that appear in the editing mode. Use the cursor to drag the guides to the proper locations to isolate the circles in the corners.
  7. Return to the Stage to view the instance again. Scale it to a larger size using the Free Transform tool. Notice that the circles in the corners do not scale and that the stroke weight remains the same.

    9-Slice Scaling

    Figure 6. Guides available for placement while editing within a symbol with 9-slice scaling enabled

See the following section of the Flash LiveDocs for more information on 9-slice scaling: Using Flash > Using symbols, instances, and library assets > Scaling and caching symbols > About 9-slide scaling and movie clip symbols.

Where to go from here

To learn more and explore what you can do with graphic effects in Flash, check out the following more advanced resources:

About the authors

This content was authored by Adobe Systems, Inc.
Jen deHaan, a rather awkward and uncool Canadian, likes robots and pirates (as well as robotic pirates). Jen works on documentation at Macromedia in San Francisco. She also maintains a blog at weblogs.macromedia.com/dehaan and believes that _root and low-carb diets are unusually evil.

Dan Carr is owner, lead developer, and trainer for Dan Carr Design in San Francisco. With years of history developing for Macromedia and Adobe, Dan has created a range of features available in Flash, including e-learning templates, UI components, and Developer Resource Kit extensions. Dan teaches Flash design and ActionScript classes in San Francisco and develops e-learning and web applications for the public, as well as for Adobe product teams.