AS3 Basics: Creating Random BitmapData in Actionscript 3

Flash CS3 Professional

Ah everybody loves bitmaps, without them the web would be boring, well kinda. Anyway the following code will create the movie bellow.

This movie creates a bitmapdata object and randomise the colour of each pixel at runtime.

And heres the code to do it! step by step. (Skip to the bottom if you just want the source :P )

// initial width and height of our new bitmapData
var bitWidth:int = 100;
var bitHeight:int = 100;

These few lines define the width and height of our new bitmap.

// create bitmap data
var myBitmapData:BitmapData = new BitmapData(bitWidth, bitHeight, false, 0x000000);

Now we instantiate  the bitmapdata class. This will hold all our bitmap data (woo)

// create bitmap
var myBitmap:Bitmap = new Bitmap(myBitmapData);

Add our bitmapdata to the bitmap

var myBitmapHolder:Sprite = new Sprite;

Create a new sprite to hold our bitmap (so we can scale it)

stage.addChild(myBitmapHolder);
myBitmapHolder.scaleX = myBitmapHolder.scaleY = 4;// 4x width and hieght == 400px (the width of the stage)

Add the sprite to the stage and scale it.

myBitmapHolder.addChild(myBitmap);

Add the bitmap to the holder.

Now for the interesting bit!

for (var i = 0; i<bitWidth; i++)
{
    for (var j = 0; j<bitHeight; j++)
    {
        myBitmapData.setPixel(i, j, Math.random()*0xFFFFFF);
    }
}

This peice of code iterates through every pixel and runs an update on its colour based on a random number.

horray! you are complete!

Tags: , , , , ,

  • http://ponero.wordpress.com/2009/03/23/links-for-2009-03-23/ links for 2009-03-23 « JUS IN BELLO

    [...] Wuup | AS3 Basics: Creating Random BitmapData in Actionscript 3 (tags: flash bitmap) [...]