Recipe 8.8.
Copying Pixels
Problem
You
want to copy a rectangular
area from one BitmapData to another.
Solution
Use the copyPixels( ) method of the
BitmapData class.
Discussion
The theory behind the copyPixels( )
method is quite simple. It takes the pixel data from one bitmap and
draws it onto another. In that sense, it is much like the draw(
) method. However, in the case of copyPixels( ), you get
more control over how much of the bitmap is copied and where it is
copied to. You do this by specifying a source rectangle and a
destination point:
bitmap.copyPixels(sourceBmp, srcRect, destPoint);
The source rectangle is an instance of the
flash.geom.Rectangle
class. You use this to define a rectangular area of the original
BitmapData. This is the only portion of that bitmap that is
copied.
The destination point is an instance of
flash.geom.Point. This specifies the x, y
coordinate of the destination bitmap where you want to paste the
copied pixels.
The following example shows how to copy several
rectangular areas of a loaded bitmap onto another
BitmapData:
package {
import flash.display.Sprite;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.geom.Point;
import flash.geom.Rectangle;
public class AS3CB extends Sprite {
private var _bitmap:BitmapData;
private var _loader:Loader;
public function AS3CB( ) {
_loader = new Loader( );
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoad);
_loader.load(new URLRequest("myphoto.jpg"));
_bitmap = new BitmapData(stage.stageWidth,
stage.stageHeight,
false, 0xffffffff);
var image:Bitmap = new Bitmap(_bitmap);
addChild(image);
}
public function onLoad(event:Event):void {
var loaderBmp:Bitmap = Bitmap(_loader.content);
var w:Number = loaderBmp.width / 10;
for(var i:int = 0; i < 10; i++) {
_bitmap.copyPixels(loaderBmp.bitmapData,
new Rectangle(i * w, 0,
w, loaderBmp.height),
new Point(i * (w + 2), i));
}
}
}
}
In the preceding code, the important part is
highlighted in bold.
The defined rectangle copies progressive
vertical strips from the loaded image, and the point places them in
the new bitmap, spaced out by a couple of extra pixels.
There are a few more optional parameters. You
can specify another BitmapData to use as an alpha channel,
and you can choose to blend the alpha levels of the existing and
new alpha bitmap. The syntax for this is:
bitmap.copyPixels(sourceBmp, srcRect, destPoint,
alphaBmp, alphaDestRect, blend);
This is a more advanced use of the metho. We
won't cover it here in detail, but you are free to experiment with
it on your own.
See Also
Recipes 8.5,
8.6,
8.7,
8.9,
8.10,
and 8.11
for other ways to add graphical content to a bitmap.
|