How to use Bitmap and BitmapData in ActionScript 3 – v2

Apr
23


Alright, in this example, I am cutting each pixel in an image and piecing it back together again. Only this time I animating the pixel to a new location, piecing back the image at 200%. I think this can open a lot doors in what you can do with a bitmap.

Here is the Bitmap test 2 example

bitmaptest2.fla

Here is the code

[as]import flash.display.*;
import caurina.transitions.Tweener;
//holds all the pixels
var pixHolder:Sprite = new Sprite();
//linkage to img in library
var img:Img = new Img();

addChild(pixHolder);

//array that will hold info of each pixel
var pixels_array:Array = [];
//bitmapdata of the img
var bmd:BitmapData = new BitmapData(img.width, img.height, false);
//put the img bitmapdata in the new bitmapdata object
bmd.draw(img, new Matrix());
//I heard this helps performance
bmd.lock();
//loop thru each pixel
//i.e. i= 0; j = 0 then i=1; j = 0 then i = 2; j = 0 you get it right?
for (var i:int = 0; i < img.width; i++)
{
for (var j:int = 0; j < img.height; j++)
{
//create an obj to hold each pixels info
var coords:Object = {};

//in this example I decided to use a rect graphic instead of a single bitmap
//for fun
var pixSprite:Sprite = new Sprite();
//make a pixSprite for each pixel
pixSprite.graphics.beginFill(bmd.getPixel(i, j), 1);

pixSprite.graphics.drawRect(0, 0, 1, 1);
pixSprite.graphics.endFill();
// add an event listener to each pixel to animate
pixSprite.addEventListener(MouseEvent.MOUSE_OVER, updating, false, 0, true);
//put pixels in their right place
pixSprite.x = i;
pixSprite.y = j;
pixHolder.addChild(pixSprite);
}
}

bmd.unlock();
//you don’t need the data in memory any more
bmd.dispose();

function updating(evt:MouseEvent):void
{
//the moused over pixel removes listener, scales 200% and moves down to make a img at 200%
evt.currentTarget.removeEventListener(MouseEvent.MOUSE_OVER, updating);
trace(“over”);
Tweener.addTween(evt.currentTarget, {scaleX:2, scaleY:2, x: img.width + evt.currentTarget.x * 2, y: img.height + evt.currentTarget.y * 2, transition:”linear”, time:.5});
}

[/as]

 

Leave a Reply