BitmapData lock() & unlock()

var size:Number = 400;
var pixelNum:Number = size * size;
var pixels:Vector.<uint> = new Vector.<uint>();
var r:uint;
var g:uint;
var b:uint;

var canvas:BitmapData = new BitmapData(size,size,false,0x000000);
addChild(new Bitmap(canvas));

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {

	canvas.lock();

	// do any kind of pixel manipulation here:
	
	for (var i:int = 0; i<pixelNum; i++) {
		// draw a gradient that changes based on
	    // mouse position
		r = i % size + mouseX;
		b = i / size + mouseY;
		g = (r + b) % mouseX;
		pixels[i] = r << 16 | g << 8 | b;
	}
	canvas.setVector(canvas.rect, pixels);
	//

	canvas.unlock();
}

Using BitmapData.lock() and BitmapData.unlock() can speed up BitmaData drawing operations significantly. Simply lock your BitmapData before you draw to it, and unlock it when your done.

I often forget to do this until I get to the optimize phase of a project… but I think I’d like to get in the habit of doing it all the time….

2 comments

Leave a Reply

Your email address will not be published. Required fields are marked *