13 February 2012
General knowledge of using the Flash Professional workspace and a basic understanding of concepts needed to use ActionScript 3 in Flash.
All
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.
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.
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.
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.
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).
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.
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:
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.
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.
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.
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:
You'll also explore these runtime ActionScript 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.
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).
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.
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.
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.
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.
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.
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:
Follow these steps to set up the background image:
Follow these steps to edit the bitmap file outside of Flash:
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.
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:
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:
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.
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.
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;
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);
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.
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:
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.geom.Rectangle;
import flash.geom.Matrix;
// 1. Add symbol to stage
var target:MovieClip = new WalkCycle();
target.scaleX = 2;
target.scaleY = 2;
addChild(target);
// 2. Go to a frame in the symbol
target.gotoAndStop(10);
// 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);
// 4. Render Bitmap instance
var bmp:Bitmap = new Bitmap(bmpData);
bmp.x = (1024-bmp.width)/2;
bmp.y = (600-bmp.height)/2;
addChild(bmp);
// 5. Remove symbol from the Stage
removeChild(target);
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.
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:
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.
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);
// 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;
}
// 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;
}
// 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);
// 6. Create a function to show frames
function showFrame( fr:uint ):void
{
bmp.bitmapData = frameData[fr];
}
var frame:uint = 0;
showFrame(frame);
// 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);
In a full-scale solution, you would continue adding scripts to include memory optimization, as well as adding other fine-tuned features.
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:
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.
| 04/23/2012 | Auto-Save and Auto-Recovery |
|---|---|
| 04/23/2012 | Open hyperlinks in new window/tab/pop-up ? |
| 04/21/2012 | PNG transparencies glitched |
| 04/01/2010 | Workaround for JSFL shape selection bug? |
| 02/13/2012 | Randomize an array |
|---|---|
| 02/11/2012 | How to create a Facebook fan page with Flash |
| 02/08/2012 | Digital Clock |
| 01/18/2012 | Recording webcam video & audio in a flv file on local drive |