
Beginning ActionScript 2.0 2006
.pdf
Chapter 15
dispose() explicitly frees RAM being used by the Bitmap object. It is important to understand this aspect of the Bitmap object. When declaring a bitmap, Flash is using RAM, whether or not pixel data has been defined. How much RAM is utilized depends on the size of the bitmap declared in the bitmapData constructor. Once there, you must call the dispose() method for that RAM to be freed. If you don’t, you potentially cause a severe memory leak, or even worse, a system crash. This issue can easily arise when creating bitmaps in loops or if you’re sloppy about caring what happens to the object once it’s off the stage. You must be conscious of the RAM usage your SWF file exhibits. Always test, test, and test again on your target systems.
draw()
The draw() method copies the current pixels in a source object into the original bitmap image.
The parameters of draw are source:Object; matrix:Matrix; colorTransform:ColorTransform; blendMode:Object; clipRect:Rectangle; and smooth:Boolean:
source — Specifies the object from which to obtain the bitmap. If you specify a movie clip, a snapshot is taken of the current state of the movie clip. If the movie clip has any matrix transformation applied, such as distort, the transform is ignored. The bitmap is created with the transform state of the movie clip as it originally existed.
matrix — A matrix object. The matrix object is generally used to change the image, such as rotate or scale. You can use this to reapply transforms, which are lost when the source object is defined, or you can define a new matrix object. You can always apply the matrix object later, if you leave this parameter blank.
colorTransform — A colorTransform object defined by the flash.geom.colorTransform object.
clipRect — A flash.geom.rectangle object specifying the section or clipping of the movie clip from which to obtain pixels. If you do not specify this parameter, the entire source is used.
blendMode — A blendMode object that describes how the Bitmap object should blend with the pixels that reside behind it.
fillRect()
The fillRect() method creates a rectangle with a specified color. The rectangle is defined as a flash.geom.rectangle object. This method is useful for specifying the initial bitmap size when performing certain filter and pixel renderings.
The parameters of fillRect are rectangleObject:Rectangle and color:Number:
rectangleObject — A flash.geom.rectangle object. The rectangle object can be created separately and created as a variable. You must import the flash.geom.rectangle class.
color — A hexadecimal number in the ARGB format 0xAARRGGBB.
floodFill()
floodFill() works very much like the flood fill tools in various image editing programs. The first two parameters are x and y properties. The last parameter is an AARRGGBB number. The method fills any pixels that match and touch the pixel at the specified x,y location.
358

Working Directly with Bitmap Data
The parameters of floodFill are x:Number; y:Number; and color:Number:
x — The x position of the pixel, which will be the index for the flood fill.
y — The y position of the pixel, which will be the index for the flood fill.
color — A hexadecimal number in the format 0xAARRGGBB.
generateFilterRect()
The generateFilterRect() method provides a simple rectangle output. However, the rectangle is the final size after a bitmap has a filter run against it. This is important because it doesn’t actually run the filter. The method merely reports back what to expect in size difference after you’ve run a filter. This is helpful when creating a user interface that needs to grow and expand depending on the filters might be on a specific movie clip. A movie clip section that has a drop shadow, for example, is slightly larger than it is without a filter. You might want to adjust your user interface for the difference so you don’t get any strange overlapping. The parameters are simple. You supply the rectangle object, which will receive the filter, and you provide the filter.
The parameters of generateFilterRect are rectangleObject:Rectangle and filter:BitmapFilter:
rectangleObject — A flash.geom.rectangle object. The rectangle object can be created separately and created as a variable. You must import the flash.geom.rectangle class. The rectangle defines an area within a larger bitmap to apply the filter.
filter — A filter object. (Filters are discussed in Chapter 14.)
getColorBoundsRect()
The getColorBoundsRect() method returns a rectangle that defines the area of color specified. The color is specified as a mask and color. This method is useful for finding the exact visible edges of a bitmap or discovering whether an image has a border that should be ignored.
The parameters of getColorBoundsRect are mask:Number; color:Number; and findColor:Boolean:
mask — A hexadecimal number in the format 0xAARRGGBB. This color defines the threshold at which to ignore a color range.
color — A hexadecimal number in the format 0xAARRGGBB. This color defines the maximum threshold value to search for. For example, to find any values that have no alpha value, you would define mask as 0xFF000000 and color as 0x00000000.
findColor — A Boolean. If true, it returns the bounds of where the color range exists within the image. If false, the rectangle defines where the color value isn’t present in the image.
getPixel()
The getPixel() method returns the RGB color of a specific pixel in a bitmap. This is especially useful for video and webcam effects where you’d want to track specific colors or thresholds. The return value is a pre-multiplied RRGGBB number. You must run the color through a simple operator function to obtain individual values. You see this function in action later in the chapter.
359

Chapter 15
The parameters of getPixel are x:Number and y:Number:
x — The x coordinate of the pixel to examine.
y — The y coordinate of the pixel to examine.
getPixel32()
The getPixel32() method is similar to getPixel(), but it also returns a number with the alpha value multiplied with the RRGGBB values. It is helpful for specific effects where you’d like to track a specific color.
The parameters of getPixel32 are x:Number and y:Number:
x — The x coordinate of the pixel to examine.
y — The y coordinate of the pixel to examine.
hitTest()
hitTest() is almost identical to the movieclip.hittest method, although it is much more powerful in that you can detect alpha threshold values. It means you can actually obtain shape-specific hitTest results, which is fantastic news for game coders.
The parameters of hitTest are firstPoint:Point; firstAlphaThreshold:Number; secondObject:Object; secondBitmapPoint:Point; and secondAlphaThreshold:Number:
firstPoint — The first point in the target bitmap that should be tested for a hitTest.
firstAlphaThreshold — The alpha threshold value that qualifies as a hit from the firstPoint value. The parameter expects a value of 0–255. If no value is given, 255 is assumed.
secondObject — Can be a rectangle, a point, or a full Bitmap object.
secondBitmapPoint — When the secondObject is defined as a Bitmap object, this parameter provides a specific start point within the bitmap to begin checking for the hitTest.
secondAlphaThreshold — When the secondObject parameter is defined as a bitmap, this parameter defines the alpha value that qualifies for a hitTest to return true. The parameter expects a value of 0–255. If no value is given, 255 is assumed.
loadBitmap()
loadBitmap() is similar to the movielcip.attachMovie method. The parameter is a linkage ID of a Bitmap object such as a PNG that resides in the library and has been exported for ActionScript access. This method does not “show” the bitmap on the stage. You must still use the attachBitmap object on a movieClip symbol to give the bitmap a place to reside.
The parameter of loadBitmap is libraryId:String. The string matches a linkage ID that exists in the library. The library symbol must be a Bitmap object.
360

Working Directly with Bitmap Data
merge()
The merge() method evenly merges two bitmap images to create one image. Each channel is specified with a multiplier by which the pixel color values will be modified.
The merge() method performs the following algorithm on each pixel and channel:
Final red value = (red channel from the source image * the specified red channel multiplier) + (red channel from the destination image * (256 – the specified red channel multiplier) / 256;
The exact inner workings aren’t as important to know as that the algorithm produces an evenly blended pixel color value as a result of both images.
The parameters of merge are sourceBitmap:BitmapData; sourceRect:Rectangle; destPoint:Point; redMult:Number; greenMult:Number; blueMult:Number; and alphaMult:Number:
sourceBitmap — The bitmap to merge into the existing bitmap. This object can be a different bitmap, or it can be the same bitmap image. Using the same bitmap can be useful for interesting pattern affects and animations.
sourceRect — This parameter is a flash.geom.rectangle object. The rectangle defines the rectangle area of the sourceBitmap to use for the merge.
destPoint — This parameter is a flash.geom.point object. The parameter is the start point in the original image to begin merging in the source bitmap.
redMultiplier — This parameter is a Number. The number multiplies the red channel of the pixel being merged.
blueMultiplier — This parameter is a Number. The number multiplies the blue channel of the pixel being merged.
greenMultiplier — This parameter is a Number. The number multiplies the green channel of the pixel being merged.
alphaMultiplier — This parameter is a Number. The number multiplies the alpha channel of the pixel being merged.
noise()
The noise() method efficiently produces a noise effect on the specified bitmap rectangle. The effect is similar to the noise effect found in popular image editing programs.
The parameters of noise are randomSeed:Number; low:Number; high:Number; channelOptions:Number; and grayScale:Boolean:
randomSeed — An index that controls the randomness of the noise effect.
Low — The lowest color channel value to utilize in the noise effect. The parameter expects a value of 0–255.
361

Chapter 15
High — The highest color channel value to utilize in the noise effect. The parameter expects a value of 0–255.
channelOptions — This special parameter uses the logical OR operator. You can specify four channels from which the randomSeed can manipulate: 1 (red), 2 (green), 4 (blue), and 8 (alpha). For example, to allow the random function to choose red or blue, you’d use: (1|2). A random function that uses all channels, including alpha variations, is (1|2|4|8). Because this is a logical operator, do not set this as a string.
grayscale — If true, each color channel is set to the same value, effectively gray-scaling the image. The default is false, which allows for full color.
paletteMap()
paletteMap() is used for color channel manipulation. This method is very helpful in controlling the overall hue of the image. It can be used to remap a color palette from one bitmap onto another. Otherwise, you can specify array values to which the original image should be mapped.
The parameters of paletteMap are sourceBitmap:BitmapData; sourceRect:Rectangle; destPoint:Point; redArray:Array; greenArray:Array; blueArray:Array; and alphaArray:Array:
sourceBitmap — The source bitmap from which color should be obtained. If the source is the same as the original, you need to specify the color array parameters.
sourceRect — A flash.geom.rectangle object. Use this to limit the palette to a specific set within the source bitmap.
destPoint — A flash.geom.point object specifying where in the bitmap to begin manipulating the original Bitmap object.
redArray — Represents the new red array values in which 255 maps to a hexadecimal value that represents the maximum red value of the array.
greenArray — Represents the new green array values in which 255 maps to a hexadecimal value that represents the maximum green value of the array.
blueArray — Represents the new blue array values in which 255 maps to a hexadecimal value that represents the maximum blue value of the array.
alphaArray — Represents the new alpha array values in which 255 maps to a hexadecimal value that represents the maximum alpha value of the array.
perlinNoise()
The perlinNoise() method produces Perlin noise, which differs from the regular noise filter in that it uses mathematics to produce more natural random effects where clumping or thin areas can occur. Perlin noise is considered to be natural noise, whereas noise that is evenly spread out is considered to be a controlled random field, not as random as Perlin noise. It is used to generate fake terrain or mimic natural phenomenon such as flowering plant distribution in a field. It produces very realistic distribution when natural randomness is more desired over homogenized random noise. You can check out more indepth mathematical theories with Perlin noise if you’re interested. For now, you can assume this function works as expected, and you can use it to do many things, such as randomly place movie clips within a parent movie clip or generate displacement maps for terrain generation.
362

Working Directly with Bitmap Data
The parameters of perlinNoise are baseX:Number; baseY:Number; numOctaves:Number; randomSeed:Number; stitch:Boolean; fractalNoise:Boolean; channelOptions:Number; grayScale:Boolean; and offsets:Object:
baseX and baseY — Unique parameters specifying the frequency that should be used to place a point. For example, a wide image should have a wide baseX for more even distribution of the noise.
numOctave — Much like musical octaves. The more octaves in music, the more varied the sound result can be. Here, the more octaves, the more levels of detail can be achieved in the random field.
randomSeed — The value by which the random value is calculated. The perlinNoise function is not truly random. If you keep all the values the same, including the randomSeed, you obtain exactly the same results every time. Change the randomSeed and the results will vary within the field. Keeping the randomSeed the same and merely changing the available octaves simply changes the detail of the Perlin noise and not the overall random field. This is useful for constructing and returning to the same random field.
stitch — A Boolean. If true, the noise generator attempts to end edges so that the result can be tiled
fractalNoise — A Boolean. If true, this parameter causes randomly generated areas to be more evenly generated, where the contrast areas are smoothed using fractal interpolation. If false, the gradients between high contrast values can have large gaps causing cliff-like effects that allow for high-contrast terrain such as water or mountainous regions.
channelOptions — This special parameter uses the logical OR operator. You can specify four channels from which the randomSeed can manipulate: 1 (red), 2 (green), 4 (blue), and 8 (alpha). For example, to allow the random function to choose red or blue, you’d use: (1|2). A random function that uses all channels, including alpha variations, is (1|2|4|8). Because this is a logical operator, do not set this as a string.
grayscale — If true, each color channel is set to the same value, effectively gray-scaling the image. The default is false, which allows for full color.
offsets — An array that represents a point as [x,y]. The value offsets the effect of the numOctave value by specific x and y values upon the original bitmap image. offsets is useful for smoothly sliding a Perlin noise effect into an image.
pixelDissolve()
The pixelDissolve() method can be used in conjunction with a loop event to slowly dissolve a bitmap from an original set of pixels to a defined source of pixels. It can quickly and easily complete dissolve tween effects without overly affecting processor usage.
The parameters of pixelDissolve are sourceBitmap:BitmapData; sourceRect:Rectangle; destPoint:Point; randomSeed:Number; numberOfPixels:Number; and fillColor:Number:
sourceBitmap — Defines a bitmap from which replacement pixels should be sourced.
sourceRect — A flash.geom.rectangle object that defines an area within the sourceBitmap from which to source pixels.
363

Chapter 15
destPoint — A flash.geom.point object that defines where in the original bitmap image the method should begin applying sourced pixels.
randomSeed — A Number that defines the seed be used to randomly disperse the new sourced pixels into the original bitmap.
numberOfpixels — The number of pixels to replace in the original image with the sourced pixels. By looping the method in an iterative manner, you can slowly replace all pixels by choosing a number such as 30. If this parameter is not used, a fraction (1/30) of the source rectangle size is used.
fillColor — A hexadecimal color in 0xAARRGGBB format. This color will replace the destination color if the original and source pixel are identical. Use fillColor to replace specific color areas. It can be especially useful in completing dissolve effects on video and motion.
scroll()
The scroll() method can be used to scroll the visible pixels within a specified bitmap rectangle, which can have alpha 0. This is useful for scrolling a known bitmap into position without affecting its actual x and y coordinates.
The parameters of scroll are x:Number and y:Number:
x — A Number that specifies how much to offset the bitmap data within the Bitmap object horizontally.
y — A Number that specifies how much to offset the bitmap data within the Bitmap object vertically.
setPixel()
setPixel() is a method that Flash coders have sought for ages. So here it is, and it’s everything that was hoped for. It creates an actual pixel on the specified x, y coordinate in the bitmap with the color specified. If a color already exists at the point specified, the new color takes its place with no merge or effects.
The parameters of setPixel are x:Number; y:Number; and color:Number:
x — A Number specifying the x coordinate to place the color pixel.
y — A Number specifying the y coordinate to place the color pixel.
color — A hexadecimal number in the format 0xRRGGBB. This method does not support alpha channels. If you want to use alpha channels, use the setPixel32() method.
setPixel32()
The setPixel32() method is similar to setPixel(), but it supports setting the alpha value of the specified pixel.
The parameters of setPixel32 are x:Number; y:Number; and color:Number:
364

Working Directly with Bitmap Data
x — A Number specifying the x coordinate to place the color pixel.
y — A Number specifying the y coordinate to place the color pixel.
color — A hexadecimal number in the format 0xAARRGGBB. This method supports alpha channels.
threshold()
The threshold() method enables you to replace color values based on testing each pixel for a specific threshold or range of value. If true, the pixel will be replaced with the new color. The method uses logical operators to determine which operation to perform.
The parameters of threshold are sourceBitmap:BitmapData; sourceRectangle:Rectangle; destPoint:Point; operation:String; threshold:Number; color:Number; mask:Number; and copySource:Boolean:
sourceBitmap — The bitmap that will be tested for threshold. You can specify the original bitmap to perform the operation on the bitmap the method is called upon.
sourceRectangle — A flash.geom.rectangle object that defines the area in the source image to begin finding threshold values.
destPoint — A flash.geom.point object that defines where in the original image the color operation should begin taking place.
operation — A logical operator that is passed as a string. Acceptable values are “<=”, “<”,
“==”,”>”, “>=”, and “!=”.
threshold — A hexadecimal number in the format 0xAARRGGBB. This is the color value against which the logical operator tests.
color — A hexadecimal number in 0xAARRGGBB format. This color value will replace the original pixel color if the threshold test succeeds.
mask — A hexadecimal number in 0xAARRGGBB format. The number is used to isolate a specific channel within a color. For example, a value of 0xFFFFFF allows all channels, whereas a value of 0x00FF00 allows only green values to test true. This enables you to explicitly mask channels.
copySource — A Boolean. If set to true, the pixel value of the source image will be used when the threshold fails. If set to false, the pixel will not be manipulated in the original bitmap.
The bitmapData Object’s Properties
The bitmapData object has five properties:
height — The height of the bitmap, in pixels, to allocate. Setting this value does not necessarily mean you will see a pixel change on the stage.
width — The width of the bitmap, in pixels, to allocate. Setting this value does not necessarily mean you will see a pixel change on the stage.
transparent — Specifies whether the bitmap should have the capability to utilize a 32-bit alpha channel on its pixels.
365

Chapter 15
fillColor — A 32-bit color value set as RGBA, or 0xRRGGBBAA. A bitmap with a fillColor specified will show this color regardless of whether pixels have been explicitly defined within the bitmap. The area of color is determined by the height and width parameters.
rectangle — A read-only property that returns the size of the bitmap as a rectangle type object.
These properties can be set in the constructor.
Converting a Movie Clip into a Bitmap Image
Often, you might want a movie clip to continue to play while you manipulate it with bitmap filters and pixel examination. You can do this by capturing the movie clip into a Bitmap object and performing pixel functions upon the surrogate bitmap while modifying the actual movie clip.
Drawing a movie clip into a bitmap is exceptionally easy. A bitmap is defined, and a movie clip snapshot is placed into the bitmap using the draw() method, like this:
var myBitmap:BitmapData = new BitmapData(400, 400); myBitmap.draw(myClip_mc);
While this draws the pixels of the movie clip into the bitmap, the bitmap will not be visible. You can work with the pixels of the bitmap while it remains invisible, or you can show the bitmap by attaching it to an existing movie clip. Here’s an example:
var myBitmap:BitmapData = new BitmapData(400, 400); myBitmap.draw(myClip_mc); this.createEmptyMovieClip(“mybitmapCopy”, 1); mybitmapCopy.attachBitmap(myBitmap, 0);
Manipulating Bitmap Data
As described earlier, you can directly manipulate the pixels in a bitmap. You also can apply filters and blend modes to a Bitmap object. The new getPixel() and setPixel() methods enable direct control over pixels in a movie clip, allowing for interesting and exciting tween possibilities. Now you can do more than ever to the user interface (UI) on a code level and at a much faster rate than in any other Flash player before version 8.
Try It Out |
Blur a Specific Area in a Bitmap Object |
In this example you quickly create a Bitmap object using the draw method to copy a movie clip. You need an image to import onto the stage, which can be used to show a blur.
1.Open a new Flash Document. Save it as bitmapBlur.fla in your work folder.
2.Select File Import Import to Stage.
3.Navigate to an image on your drive and select it.
4.After the image is on the stage, select the instance so that it is focused.
366

Working Directly with Bitmap Data
5.Select Modify Convert to Symbol.
6.Select Movieclip as the symbol type and give your instance a logical name for the library, such as sampleImage.
7.With the movie clip selected, change its name in the properties panel to clip1. You’ll use this name to reference your image in the ActionScript. Slide the movie clip offstage. It doesn’t need to be on the stage. The stage will hold the bitmap.
8.Click the first frame in the timeline, open the Actions panel, and type in the following ActionScript:
import flash.filters.BlurFilter; import flash.display.BitmapData; import flash.geom.Rectangle; import flash.geom.Point;
var myBitmap:BitmapData = new BitmapData(clip1._width, clip1._height); myBitmap.draw(clip1);
this.createEmptyMovieClip(“copy1”, 0); copy1.attachBitmap(myBitmap, 0);
9.Test your movie now and check the stage. You should see a copy of your movie clip ready for manipulation. Close the .swf and return to the first frame ActionScript.
10.Now add the code to define a BlurFilter object. Click the first frame in the timeline, open the Actions panel (Window Actions) and enter the following ActionScript below the code added in step 8:
var myBlur:BlurFilter = new BlurFilter(); myBlur.blurX = 3;
myBlur.blurY = 3; myBlur.quality = 12;
11.Do something interesting with your filter. Rather than produce a static effect, the following function redraws the bitmap and apply the blur in a new position with each iteration. Enter the following ActionScript below the code you added in step 10:
function moveBlur() { myBitmap.draw(clip1); if (xpos<300) {
xpos += 2; } else {
clearInterval(moveblur_interval);
}
myBitmap.applyFilter(myBitmap, new Rectangle(xpos, 30, 100, 280), new Point(xpos, 30), myBlur);
updateAfterEvent();
}
moveblur_interval = setInterval(this, “moveBlur”, 10);
12.Test your movie now and check the stage. You should see a copy of your movie clip being blurred by a rectangle. Close the .swf and return to the first frame ActionScript.
13.To modify the code to add a permanent blur effect on the bitmap, go back to the code you added in step 11 and remove the following line:
myBitmap.draw(clip1);
367