BitmapData lock() & unlock()

Actionscript:
  1. var size:Number = 400;
  2. var pixelNum:Number = size * size;
  3. var pixels:Vector.<uint> = new Vector.<uint>();
  4. var r:uint;
  5. var g:uint;
  6. var b:uint;
  7.  
  8. var canvas:BitmapData = new BitmapData(size,size,false,0x000000);
  9. addChild(new Bitmap(canvas));
  10.  
  11. addEventListener(Event.ENTER_FRAME, onLoop);
  12. function onLoop(evt:Event):void {
  13.  
  14.     canvas.lock();
  15.  
  16.     // do any kind of pixel manipulation here:
  17.    
  18.     for (var i:int = 0; i<pixelNum; i++) {
  19.         // draw a gradient that changes based on
  20.         // mouse position
  21.         r = i % size + mouseX;
  22.         b = i / size + mouseY;
  23.         g = (r + b) % mouseX;
  24.         pixels[i] = r <<16 | g <<8 | b;
  25.     }
  26.     canvas.setVector(canvas.rect, pixels);
  27.     //
  28.  
  29.     canvas.unlock();
  30. }

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....

This entry was posted in BitmapData, pixel manipulation and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted July 9, 2010 at 6:08 am | Permalink

    If I unlock a bitmapData no longer, what will happen.Is Flash Player will not render the bitmap with new data.?

  2. Posted August 11, 2010 at 9:49 pm | Permalink

    Yes, Flash Player will not render the bitmap with new data.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*