By Dan Carr
 
Created
14 February 2012
 

Requirements

 
Prerequisite knowledge

General knowledge of using the Flash Professional workspace and a basic understanding of concepts needed to use ActionScript 3 in Flash.
 

 
User level

All
 

 
Required products

 
Sample files

As Adobe Flash Professional has grown into a powerful application and game development environment, so has the need to understand media characteristics and related performance optimizations. Working with vector and bitmap images is a fundamental part of visual design in Flash. Image rasterization refers to the process of converting vector graphics into bitmap graphics for performance optimization.
 
This article explores the pros and cons of using vector and bitmap graphics, as well as the options available for rasterizing images. You'll find a series of simple exercises illustrating  how to set up and use the rasterization features at author-time and runtime (click Figure 1). Along the way, you'll learn how to work with the new Export as Bitmap feature—while learning how to use the BitmapData object in ActionScript 3.
 
Figure 1. Examples of bitmaps rendered through the exercises in this article
Figure 1. Examples of bitmaps rendered through the exercises in this article

 
Understanding vectors and bitmaps

Images in Flash come in two flavors: vector images and bitmap images. Each format has advantages and drawbacks. In this section, you'll learn about each format, the pros and cons of each format, and when it is appropriate to use each format.
 
 
What is a vector graphic?
A vector graphic is a shape drawn with a series of points and lines connecting the points (see Figure 2). For example, a square consists of four corner points with lines connecting each point. A circle contains the same four points, but the lines between them are curved instead of straight. A vector shape has a fill color and an outline (stroke) color. Usually a vector graphic is composed of dozens or more vector shapes that overlap to form a picture.
 
Figure 2. The points and lines that define a square and a circle vector image
Figure 2. The points and lines that define a square and a circle vector image
Vector graphics have the advantage of being light-weight and scalable. Under the hood, vector graphics are defined entirely by the math describing their points and lines, so they are not composed of resolution. As a result, vector graphics are light-weight and can be scaled up and down in size without losing their quality. And vector graphics can be edited and changed at any time.
 
Vector graphics have the disadvantage of being processor-intensive in some situations. Vector graphics are rendered by the CPU at runtime and have to be re-rendered whenever a change in the graphic occurs. For example, when a vector graphic is used in a tween animation, or if the vector graphic on Stage is overlapped by a tween animation, the shape is rendered again in each frame to display the changes on the screen. Most modern desktop and laptop computers don't have any problem rendering complex groups of vector graphics, but be aware that mobile devices may display visible performance issues.
 
Use vectors whenever you need to create scalable graphics, work with editable text and shapes, or when flexible content is required for animations.
 
Tip: The drawing tools in Flash Professional natively draw vector graphics, but in many cases, it is a best practice to publish the graphics as bitmaps in order to improve performance.
 
 
What is a bitmap graphic?
A bitmap graphic is an image composed of a grid of dots called pixels (see Figure 3). Each pixel contains a color. Collectively, the grid of colored pixels forms the image. The number of pixels per inch defines the resolution of an image. The common screen resolution for computer monitors is 72 dpi (dots per inch).
 
Figure 3. A magnified view of the color pixels in a bitmap image
Figure 3. A magnified view of the color pixels in a bitmap image
Bitmap graphics have the advantage of displaying highly detailed photographic content without the use of CPU rendering. Once the bitmap has downloaded to the display, it does not need to be rendered again.
 
Bitmap graphics have the disadvantage of producing larger file sizes. The resolution, number of colors, compression scheme, and dimensions of the bitmap all contribute to the file size of the image. Also, since bitmaps are defined in resolution, they cannot be scaled to larger sizes without incurring a loss of quality. Bitmaps are not editable in Flash; you can use a tool such as Photoshop or Fireworks to edit your bitmap images prior to importing them in Flash.
 
Use bitmaps for backgrounds and static images that don't need to be edited or scaled. Also, for performance reasons and portability to mobile devices, consider using bitmaps or rasterization techniques whenever possible.
 
Tip: You can rasterize vector images into bitmap images at author-time or at runtime as a strategy to optimize editable vector graphics.
 
 
Typical performance issues and their workarounds
Depending on the complexity of your Flash movie, you may find that some animations and page transitions seem sluggish or fragmented. This scenario can occur in projects when too many overlapping vector images are redrawn in every frame. The result can be inconsistent frame rates and intermittent pauses in the vector rendering.
 
Here are a few things to consider that may improve a project's performance:
 
  1. Use bitmap images for background graphics. Animations often appear on top of larger background graphics. Using bitmaps for the backgrounds will help reduce the resources required to render the graphics and minimize CPU usage.
     
  2. Large areas of animation are more likely produce performance issues. Try to limit the area an animation plays to the smallest size possible.
  3. Animations and complex graphics that use transparency (alpha) require more CPU usage than opaque graphics.
  4. Animations and complex graphics that use filters and blend modes require more CPU usage than graphics that do not. Apply filters and blend modes sparingly. Also, try to use lower quality settings when working with filters.
  5. Avoid displaying animations that constantly idle, if possible.
  6. Use the rasterization features in Flash to convert static graphics into bitmaps at author-time or runtime.
Tip: You can use ActionScript-based profiler utilities to test the performance of your movie and compare memory usage while optimizing your projects. Check out Shane McCarthy's AS3 SWF Profiler, an option that's easy to use.
 
 
Benefits of rasterizing vector graphics
Flash Professional and ActionScript 3 provide a handful of options for converting vector graphics to bitmaps. The benefit of using these features is that you can often avoid the performance pitfalls described previously while leaving your artwork editable at author-time. The result can produce projects that require less CPU usage, smoother animation performance and frame rate playback, and improved performance—especially for applications being ported to mobile devices.
 
 
Options available in Flash Professional and ActionScript 3
The following sections of this article will walk you through concepts and exercises describing the rasterization features in Flash.
 
You'll explore these author-time features:
 
  1. Cache as bitmap
  2. Export as bitmap
  3. Convert to bitmap and convert selection to bitmap
You'll also explore these runtime ActionScript features:
 
  1. Cache as bitmap
  2. Bitmap object
  3. BitmapData object

 
Working with author-time rasterization features

Flash Professional CS5.5 introduces the Export as bitmap features as an improved workflow to publish vector graphics as bitmaps in the SWF file. This feature, combined with the pre-existing cache as bitmap and convert to bitmap features, offer powerful, easy to use options while working visually at author-time in the FLA file.
 
This section provides an overview of the author-time rasterization features in Flash.
 
 
Bitmap caching
The bitmap caching feature is one of the older rasterization features in Flash. Use bitmap caching to allow Flash Player to cache a symbol as a bitmap in RAM memory at runtime. The bitmap caching feature is easy to use. Convert an image to a symbol, make sure it's selected, and then choose the Cache as Bitmap Render option in the Display section of the Property inspector (see Figure 4).
 
Figure 4. The Cache as Bitmap option is displayed in the Property inspector while a symbol is selected.
Figure 4. The Cache as Bitmap option is displayed in the Property inspector while a symbol is selected.
The theory is that bitmap caching allows Flash Player to cache the image to avoid re-rendering the image in each frame. This feature works best when using images that do not animate, and do not have filters or blend modes applied.
 
Tip: The Cache as bitmap option can actually increase CPU usage when used with images that are part of a tween animation that scales or rotates. Animations containing complex transformations will re-cache the bitmap in each frame—causing them to require more CPU usage than simply using the original vector artwork.
 
 
Convert to bitmap
The convert to bitmap and convert selection to bitmap features are handy when you want to convert vector artwork to an actual bitmap at author-time. This feature can be applied to both symbols and drawing objects. To use the feature, select one or more graphics on the Stage and choose Modify > Convert to Bitmap. You can also right-click on the selected objects and choose the Convert to Bitmap option in the context menu that appears.
 
The convert to bitmap feature literally creates a new bitmap file in the Library from the selected items. You can capture a selection of artwork, convert it to a bitmap, and then edit the bitmap in an image-editing application, such as Photoshop (see Figure 5). After the bitmap is created, symbols are still preserved in the Library as separate editable objects. Drawing objects are no longer editable after they've been converted to a bitmap.
 
Figure 5. The context menu for a selected bitmap in the Library includes the option: Edit with Adobe Photoshop CS5.
Figure 5. The context menu for a selected bitmap in the Library includes the option: Edit with Adobe Photoshop CS5.
Use the convert to bitmap feature when you want to create a physical bitmap file that can be edited in other drawing programs and saved as an external bitmap image.
 
Tip: One of the benefits of this approach is that a bitmap item is generated in the Library. Double-click on the bitmap to launch the Bitmap Properties dialog box to adjust the compression setting and see details about the bitmap image.
 
 
Export as bitmap
The new export as bitmap feature allows you to turn any movie clip or button symbol into a bitmap at author-time (see Figure 6). When this option is enabled, Frame 1 of the symbol is displayed as the bitmap. You can set the background to transparent or opaque with a specified background color. While viewing the symbol instance, you see the Frame 1 bitmap. While editing the symbol's timeline, you see the frame actions, frames, and keyframes as expected. Unlike the convert to bitmap feature, export as bitmap allows the symbol and its contents to remain editable in the FLA file. That means you can continue editing and resizing the Flash content as needed, see the bitmap while you are authoring the file, and publish the bitmap from Frame 1 at the same time you publish the movie. When using the export as bitmap feature, a separate bitmap is not created in the Library.
 
Figure 6. While a movie clip or button symbol is selected, you can choose the Export as Bitmap option in the Property inspector.
Figure 6. While a movie clip or button symbol is selected, you can choose the Export as Bitmap option in the Property inspector.
The export as bitmap feature makes it easier to repurpose graphics across applications or banners. Use this approach when you need to port artwork, banner graphics, or UI graphics to applications that will be displayed at different screen sizes. For example, use the export as bitmap feature to resize background artwork and logos as needed across FLA files and still publish the symbol elements as static bitmaps in the SWF files you create.
 
Tip: Combining the export as bitmap feature with the author-time shared assets feature in the Project panel is a great way to distribute common assets that will be reused and resized across files in a project.
 
 
Exercise 1: Using export as bitmap and convert to bitmap
In the simplest scenario, you might find yourself working with a large vector graphic as a background that you want to publish as a bitmap. Doing so will incur additional file size, but it will allow animations and other overlapping content to play back more smoothly.
 
In this exercise, you'll import a photograph of a group of people and position it as a background image for your movie. For fun and as a special effect, you'll convert the photo to a series of vectors using the Trace Bitmap command, and then set up the adjusted photo to export as a bitmap. You'll also try using the convert to bitmap option to facilitate further editing.
 
Follow these steps to set up your project folder:
 
  1. If you haven't done so already, download the bitmap_exercises.zip file included in the source file provided at  the beginning of this article.
  2. Unzip the sample files folder and save it to your desktop. As you work, you'll open the sample files from the assets folder and save the files you create as you complete the exercises into the bitmap_exercises folder.
  3. Download the bitmap_exercises_completed.zip file to view the completed sample project files and compare your work.
Follow these steps to set up the background image:
 
  1. Create a new ActionScript 3 FLA file and save it as exercise1.fla in the project folder.
  2. Click the Stage to access the Stage properties in the Property inspector. Set the Stage size to 1024 x 600 pixels.
  3. Choose File > Import > Import to Stage to import the background.jpg image included in the sample files folder. You can import your own image if you prefer.
  4. Position the image at the 0, 0 (top left) X and Y coordinates.
  5. While the image is selected, choose Modify > Bitmap > Trace Bitmap. Adjust the settings in the Trace Bitmap dialog box and press the Preview button to see the effect (see Figure 7). This operation essentially posterizes the bitmap into a group of simplified vector shapes. Click OK to add the effect.
Figure 7. Enter the Color threshold values in the Trace Bitmap dialog box.
Figure 7. Enter the Color threshold values in the Trace Bitmap dialog box.
  1. While the vectors are still selected, press F8 to convert vector artwork to a new movie clip symbol named Background. This step is necessary in order to work with the export as bitmap feature.
  2. While the new movie clip symbol instance is selected on the Stage, change the Render setting to Export as Bitmap in the Property inspector. You can leave the bitmap background property set to Transparent, but be aware that you could also set an opaque background color if the image includes transparent areas.
  3. In the Property inspector, change the value of the alpha property of the instance to 25% to create a watermark-type background effect. If desired, you can experiment by scaling the background element larger to display close ups of the various people in the photo. Since the traced background is now comprised vector artwork, you don't have to worry about losing quality when you scale the background, because vectors are resolution independent,
  4. Choose Control > Test Movie to publish the SWF file and check your work.
  5. Save the FLA file.
Follow these steps to edit the bitmap file outside of Flash:
 
  1. Imagine that you want to save the posterized image and edit it in Photoshop or another image-editing tool. Simply select the symbol instance, right-click it, and choose the Convert to Bitmap option from the context menu that appears.
  2. Notice that the instance on the Stage is replaced by the new Bitmap 1 file that was just added to the Library.
  3. Right-click the Bitmap 1 item in the Library. Choose Edit in Adobe Photoshop CS5 or the Edit with... option in the context menu to send the bitmap to an external image editor. When you open the file in Photoshop, make a change, and then save it, the file in Flash automatically updates. In Photoshop, you can choose File > Save as to save a copy of the bitmap file to your desktop and repurpose it in other projects.
This simple exercise illustrates how you can create interesting backgrounds using posterized photographs. The export as bitmap feature leaves the vector artwork editable so that you can resize it as needed, but publishes the background as a bitmap so overlapping animations and content can run smoothly. From here, you can add content to the FLA file as desired.
 
 
Exercise 2: Creating a resizable template for a banner project
A more complex scenario might involve repurposing a background graphic across project files that use different dimensions. For example, if you were developing a banner ad campaign, you may be tasked with delivering a tagline and logo animation that displays across several different standard banner sizes. Or you might develop a game or application that will be ported to fit different screen sizes, based on web or mobile deployment requirements.
 
In this exercise, you'll develop a template you can use to create banner ads in different sizes that all use the same background texture. In this scenario, it's important to keep the file sizes well below 40k in the template. To achieve this, you'll use a scalable texture created in Illustrator. The main goal is the ability to duplicate and resize the texture as editable vectors for each banner ad, while still publishing the background graphics as bitmaps.
 
Follow these steps to set up the banner template:
 
  1. Create a new ActionScript 3 FLA file and save it as exercise2.fla in the project folder.
  2. Set the Stage dimensions to 300 x 250 pixels.
  3. Rename the default Layer 1 to background and then add a new layer above it named border.
  4. Select the border layer and draw a 1 pixel black outline around the edge of the Stage. Lock the border layer.
  5. Select the background layer and choose File > Import > Import to Stage. Browse to select the pattern.ai file in the sample files folder and then choose Open to import the file. In the Import to Stage dialog box, click OK to accept the default Illustrator import settings. Notice that after importing the file, the circle pattern appears on the Stage.
  6. Select circle graphic and position it at the top left of the Stage, using the 0, 0  coordinates. Press F8 to convert the artwork to a movie clip symbol named Background. This step enables you to resize and duplicate the pattern as needed while only turning on the export as bitmap feature once for the background instance.
  7. Double-click the background instance to edit its timeline. Scale and duplicate the pattern as needed to cover the entire Stage area.
  8. Click the Scene 1 link to return to the main Timeline. Select the background instance. While it is selected, enable the Export as Bitmap option in the Property inspector.
  9. Choose Control > Test Movie to check your work. While the SWF is still open, choose View > Bandwidth Profiler in the top menu bar. The Bandwidth Profiler panel appears and allows you to see the file size of the movie (see Figure 8). Use this approach to quickly check your file size, in order to keep the template somewhere around 10 to 20k (or less).
  10. Save the file.
Figure 8. Check the banner template SWF file with the Bandwidth Profiler.
Figure 8. Check the banner template SWF file with the Bandwidth Profiler.
Tip: There isn't any way to control the compression settings that produce the bitmap when using the export as bitmap feature. Use the Bandwidth Profiler to check the SWF's file size as you work. If you find that you need more control over the compression scheme, use the convert to bitmap feature to adjust and edit the bitmap item in the Library.
 
At this point you've set up the foundation of the banner template. From here, you can add logos, taglines, and animations to the file as needed. When you want to create a banner ad to fit different dimensions, simply choose File > Save As and save the file with a new name. Edit the new file to change the Stage dimensions, and resize the assets to fit the Stage.
 
Follow these steps to use the template to create a banner ad with different dimensions:
 
  1. Open the exercise2.fla file in Flash and choose File > Save As to save the file with a new name.
  2. In the Property inspector, change the Stage dimensions of the file to 180 x 150 pixels.
  3. Unlock the border layer and select the rectangle. Resize the shape to 180 x 150. Lock the layer again when you're finished resizing the rectangle.
  4. Select the background instance and double-click it to edit its timeline. Resize and position the pattern graphics to fit within the background area.
  5. Choose Control > Test Movie to check your work.
  6. Save the file.
So that's it. Using a template, you can continue generating new SWF files following the steps listed above. If you'd like to practice, try creating several SWF files to fit standard banner sizes at 120 x 600 pixels, 160 x 600 pixels, 728 x 90 pixels, and so on. Be sure to place any common elements, such as logos or text, in the template file so that they are ready to use when you make copies.
 
Tip: You can take this example to the next level by using the author-time shared library feature in the Flash CS5.5 Project panel. This enables you to add the Illustrator background pattern to the shared library, so that you can update all the banner files at once any time the pattern is changed. For more information on this process, see Working with Flash projects in the Flash Professional online documentation.
 

 
Working with runtime rasterization features

ActionScript 3 offers powerful options for creating and manipulating bitmaps at runtime. These features are most commonly used to create graphic effects and achieve more advanced optimization in Flash games and animation projects.
 
This section provides an overview of the runtime ActionScript options related to rasterization.
 
 
Using cacheAsBitmap
The DisplayObject class in ActionScript 3 contains the cacheAsBitmap property. It's essentially the programmatic way of enabling the cache as bitmap feature in the Property inspector while authoring FLA files. This means that you'll want to follow the same guidelines outlined above for the author-time feature. It's best to only use cacheAsBitmap on display objects that are static or do not animate using scale and rotation.
 
The cacheAsBitmap property can be applied via ActionScript to any display object. You can name the display object instance in the Property inspector and then use the following code to activate the feature:
 
myDisplayObject.cacheAsBitmap = true;
 
Using the Bitmap class
The Bitmap class in ActionScript 3 is used to represent a bitmap in code. You can either load a bitmap using the Loader object, or you can create a new Bitmap instance in code and fill it with data from a BitmapData object. The Bitmap class is usually used to data type a bitmap, unless you're creating a bitmap dynamically with BitmapData.
 
Creating an empty bitmap with ActionScript looks like this:
 
import flash.display.Bitmap; var bmp:Bitmap = new Bitmap(); addChild(bmp);
 
Using the BitmapData class
The BitmapData class is the primary tool used to manipulate bitmaps in ActionScript. You can use BitmapData to draw vector content as bitmaps, add effects to bitmaps, and perform pixel-level adjustments, calculations, and comparisons. Projects on the scale of applications and games will commonly use BitmapData and rasterization to optimize animations, page transitions, and content playback.
 
A BitmapData instance can be instantiated with four parameters: width, height, transparent, and fill color. The following code example shows how you can create a bitmap from scratch:
 
import flash.display.Bitmap; import flash.display.BitmapData; var bmpData:BitmapData = new BitmapData(50, 50, true, 0xFFFFAA00); var bmp:Bitmap = new Bitmap(bmpData); addChild(bmp);
Tip: An interesting aspect about working with BitmapData is that it can be used to manipulate the pixels of an existing bitmap, or it can be used to draw bitmaps from scratch.
 
 
Exercise 3: Rasterize a frame from a movie clip symbol using ActionScript 3
The BitmapData class can be used to generate a bitmap from any frame in a movie clip symbol. This can be a handy way to optimize and reuse graphics at runtime. Since BitmapData instances can be shared among many different bitmap instances, this approach can be used in animation and gaming projects to create repetitive scenery or game elements that require less use of RAM memory.
 
In this exercise, you'll begin working with the BitmapData class by simply creating a bitmap snapshot of vector artwork on a frame in a movie clip. Thanks to MyWeb Software for the use of the cool Lion avatar graphic used in this sample project.
 
Follow these steps to render a bitmap from vector artwork:
 
  1. Create a new ActionScript 3 FLA file and save it as exercise3.fla in the project folder.
  2. The first task involves importing the walk cycle animation. You'll start by simply capturing a frame from the animation and rendering it as a bitmap. Choose File > Import > Open External Library to show the Open as Library dialog box. Browse to the walkcycle.fla file in the assets folder of the sample files and click Open.
  3. Select the WalkCycle symbol and copy it to your clipboard. Paste the symbol into the exercise3.fla Library.
  4. Right-click the WalkCycle symbol and choose Properties in the context menu that appears. In the Symbol Properties dialog box, change the Type field to Movie Clip and enable the Export for ActionScript option. This step allows you to instantiate the symbol using ActionScript so that you can generate a bitmap snapshot. After completing this step, your Library should look like the screenshot shown in Figure 9. Notice that the AS Linkage field has been populated with the name of the symbol. You'll use the linkage name to reference the symbol in ActionScript.
Figure 9. The WalkCycle symbol as it appears in the Library after being converted to a movie clip with the Export for ActionScript option enabled.
Figure 9. The WalkCycle symbol as it appears in the Library after being converted to a movie clip with the Export for ActionScript option enabled.
  1. Change the default Layer 1 name to actions. It's a best practice to add ActionScript to the top layer in the Timeline that is dedicated specifically to contain code. In most cases, the ActionScript code will be placed on the keyframe on Frame 1 of the actions layer.
  2. Select the keyframe on Frame 1 of the actions layer. Press F9 to open the Actions panel. As you complete the next several steps, you'll add the code that generates the bitmap. Begin by adding the following code in the Script window to import the classes you'll reference in the code.
import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.MovieClip; import flash.geom.Rectangle; import flash.geom.Matrix;
  1. Copy and paste the following code to instantiate the WalkCycle symbol. You'll remove the symbol instance after you generate a bitmap from it, but at this point you can transform the vectors as desired. Notice that the code in this step creates the instance of the WalkCycle, scales it to 200%, and then adds the instance to the Stage.
// 1. Add symbol to stage var target:MovieClip = new WalkCycle(); target.scaleX = 2; target.scaleY = 2; addChild(target);
  1. Next, add the following code to send the movie clip instance to the frame you'd like to capture. In this example, you'll capture Frame 10.
// 2. Go to a frame in the symbol target.gotoAndStop(10);
  1. Add the following code to create the BitmapData instance. Notice that a bounds object and a matrix are created to account for the positioning of the artwork in the symbol. The BitmapData instance defines the box containing the bitmap in the correct position in a rectangle surrounding the artwork and then assigns it to a transparent background. The draw method copies the vector data to the BitmapData instance.>
// 3. Copy the frame to BitmapData var bounds:Rectangle = target.getBounds(this); var bmpData:BitmapData = new BitmapData(Math.floor(bounds.width), Math.floor(bounds.height), true, 0); var bmpMatrix:Matrix = target.transform.matrix; bmpMatrix.translate(-bounds.x, -bounds.y); // Draw bitmap bmpData.draw(target, bmpMatrix);
  1. Add the following code to create a bitmap to display the BitmapData. The BitmapData instance is passed to the bitmap in its constructor, and then the bitmap is positioned on the Stage.
// 4. Render Bitmap instance var bmp:Bitmap = new Bitmap(bmpData); bmp.x = (1024-bmp.width)/2; bmp.y = (600-bmp.height)/2; addChild(bmp);
  1. Finally, add this line of code to remove the WalkCycle symbol. It's no longer needed at this point.
// 5. Remove symbol from the Stage removeChild(target);
  1. Choose Control > Test Movie and check your work. You should see the artwork from Frame 10 of the Lion file appear in the center of the Stage twice as large as the original artwork.
  2. Save the file.
If you'd like to take this sample project a step further, you can experiment with generating multiple bitmaps all using the same BitmapData instance.
 
 
Exercise 4: Use BitmapData to create a bitmap animation from a vector animation
Vector animations can be sluggish, especially if they fill the screen with lots of complex content. To address this obstacle, many Flash applications and games turn to rasterization of vector content. You can essentially loop through the frames of a vector animation and render each frame as a bitmap. From there, you can play the bitmap frames back using an ENTER_FRAME event loop or a Timer interval function.
 
In this exercise, you'll generate a bitmap animation from a standard vector animation. You'll use the lion sample again and create a tween animation to move the lion's position on the Stage. Both the walk cycle and your tween will be reflected in the resulting bitmap animations.
 
Follow these steps to render a vector animation as a bitmap animation:
 
  1. Create a new ActionScript 3 FLA file and save it as exercise4.fla in the project folder.
  2. Import the walkcycle.fla Library again, if it's not already open. Copy the WalkCycle symbol from the walkcycle.fla Library and paste it into the exercise4.fla Library. This time you'll leave the WalkCycle symbol as a graphic symbol. This will allow the frames within the walk cycle animation to be synced visually to the tween animation timeline when the frames are captured as bitmaps.
  3. Press F8 to create a new movie clip symbol named WalkAnimation. Enable the Export for ActionScript option in the Create New Symbol dialog box.
  4. Double-click the WalkAnimation symbol to enter its timeline.
  5. Rename the default Layer 1 to animation. Drag an instance of the WalkCycle graphic symbol to Frame 1 of the animation layer.
  6. Extend the animation layer's timeline to 48 frames.
  7. Right-click the WalkCycle instance and choose the Create Motion Tween option in the context menu that appears. Place the playhead on Frame 48 and move the WalkCycle instance 300 pixels to the right to create the walking animation.
At this point you've created the vector-based version of the animation. The next task involves adding the ActionScript code to generate the bitmaps.
 
  1. Return to the main timeline and rename the default Layer 1 to actions. Select Frame 1 of the actions layer and open the Actions panel to add code. You'll notice that the script is similar to the code used in exercise 3. However, the example below contains additional code to capture each frame's BitmapData and play back the bitmap animation at the correct frame rate.
  2. Copy and paste the following code to import the classes you'll reference and use to instantiate the WalkAnimation symbol.
import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.MovieClip; import flash.geom.Rectangle; import flash.geom.Matrix; // 1. Add symbol to the Stage var target:MovieClip = new WalkAnimation(); target.scaleX = 1.5; target.scaleY = 1.5; addChild(target);
  1. Add the following code to find the total bounds of the animation. This step defines the rectangle that is large enough to hold all of the frames of the animation. That way, each frame ends up being the same size and the artwork on the frames lines up as expected.
// 2. Get bounds of all frames var bounds:Rectangle = target.getBounds(this); var framesTotal:uint = target.totalFrames; for(var j:uint=0; j<framesTotal; j++) { // Go to frame [j] target.gotoAndStop(j); // Map out area var frBounds:Rectangle = target.getBounds(this); if( frBounds.x < bounds.x ) bounds.x = frBounds.x; if( frBounds.y < bounds.y ) bounds.y = frBounds.y; if( frBounds.x + frBounds.width > bounds.width ) bounds.width = frBounds.x + frBounds.width; if( frBounds.y + frBounds.height > bounds.height ) bounds.height = frBounds.y + frBounds.height; }
  1. Add the following code to loop through the frames and generate a list of BitmapData objects, one for each frame. Notice that the list is defined as a Vector. A Vector is an Array where each item fits a certain data type. In this example, the data type is BitmapData. Use Vectors to speed up performance of Flash projects whenever possible.
// 3. Build BitmapData array for all frames var frameData:Vector.<BitmapData> = new Vector.<BitmapData>(framesTotal, true); for(var i:uint=0; i<framesTotal; i++) { // Go to frame [i] target.gotoAndStop(i); // Create bitmap data var bmpData:BitmapData = new BitmapData(Math.floor(bounds.width), Math.floor(bounds.height), true, 0); var bmpMatrix:Matrix = target.transform.matrix; bmpMatrix.translate(-bounds.x, -bounds.y); // Draw bitmap bmpData.draw(target, bmpMatrix); // Add to frame data... frameData[i] = bmpData; }
  1. Copy and paste the following code to remove the symbol and create the bitmap.
// 4. Remove symbol from stage removeChild(target); // 5. Create container for the animation var bmp:Bitmap = new Bitmap(); bmp.x = 150; bmp.y = (600-bmp.height)/2; addChild(bmp);
  1. Add the following code to create a showFrame function that loads a new bitmap frame. It's really cool because you can assign different BitmapData instances to the same Bitmap instance. So the Bitmap instance becomes the display object for the BitmapData frames. This step also creates a frame variable to keep track of the frames and loads the first frame to start.
// 6. Create a function to show frames function showFrame( fr:uint ):void { bmp.bitmapData = frameData[fr]; } var frame:uint = 0; showFrame(frame);
  1. Finally, add the following code to add an ENTER_FRAME event handler. This step drives the animation by displaying the next BitmapData frame every time the playhead enters a new frame on the main Timeline. Since there is only one frame on the main Timeline, the ENTER_FRAME event is called repeatedly at the FLA file's frame rate, creating a loop in that timing. The event handler increments the frame variable and resets it to 0 on the last frame to loop from the beginning.
// 7. Loop at frame rate to display animation function animationFrameHandler( event:Event ):void { frame++; if( frame == framesTotal ){// loop... frame = 0; } showFrame(frame); } addEventListener(Event.ENTER_FRAME,animationFrameHandler);
  1. Choose Control > Test Movie to check your work. The bitmap animation plays and loops through the walk cycle.
  2. Save the file.
In a full-scale solution, you would continue adding scripts to include memory optimization, as well as adding other fine-tuned features.
 

 
Where to go from here

While displaying vector content on the web has always been one of the strengths of working with Flash content, it's becoming more common these days to use bitmaps wherever possible. Consider adopting workflows that allow you to develop content using the flexibility of vector drawing tools while delivering static content as bitmaps in the final published SWF file.
 
Check out these online resources to get more information on topics described in this article:
 
Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License+Adobe Commercial Rights
 
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.