Tuesday, August 10, 2010

Working with Bitmaps in Actionscript 3: Part 3

Today we will learn how to set and get pixel values.

It is really easy to set and retrieve pixel values in Actionscript 3. To get pixel information, you need to use the getPixel method, providing x and y coordinates. To change a pixel's color, use setPixel method.

Both getPixel and setPixel methods are used for non-transparent examples of BitmapData. If you have transparency, use getPixel32 and setPixel32 methods.

Non-transparent images have 24 bits - 8 for red, 8 for green and 8 for blue. Transparent images also have an alpha-channel - 8 more bits (32 in total). Whether BitmapData supports or doesn't support alpha-channels is set when creating the BitmapData.

If you use setPixel method on a 32-bit BitmapData, alpha-channel for that pixel is automatically set to non-transparent. And, if you use setPixel32 on a 24-bit BitmapData, alpha-channel values are ignored.

Here's an example of manipulating pixels:

var bitmap:BitmapData = new BitmapData(100, 100, false, 0xffffffff);
var image:Bitmap = new Bitmap(bitmap);
addChild(image);

for(var i:int=0; i<100; i++){
bitmap.setPixel(i, i, 0xff0000);
bitmap.setPixel(i, 100-i, 0xff0000);
}

The code above shows us how to draw a red X on the screen. Finding out pixel values is just as easy:

var bitmap:BitmapData = new BitmapData(100, 100, false, 0xffffffff);
var image:Bitmap = new Bitmap(bitmap);
addChild(image);

var textf:TextField = new TextField();
addChild(textf)
textf.x=100

for(var i:int=0; i<10000; i++){
bitmap.setPixel(Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.random()*0xFFFFFF);
}

stage.addEventListener(MouseEvent.MOUSE_MOVE, lookupPixel);
function lookupPixel(MouseEvent){
 textf.text=bitmap.getPixel(mouseX, mouseY).toString(16)
 }

The code above generates a field with many random-colored pixels. Roll over a pixel to see it's value.

Thanks for reading!
Related:

Working with Bitmaps in Actionscript 3: Part 1
Working with Bitmaps in Actionscript 3: Part 2

No comments:

Post a Comment