Image Airbrush

Actionscript:
  1. [SWF(width=500, height=500, backgroundColor=0x000000, frameRate=30)]
  2.  
  3. // draw an ugly gradient
  4. var size:int = 500;
  5. var pixNum:int = size * size;
  6. var gradient:BitmapData = new BitmapData(size, size, true, 0xFF000000);
  7.  
  8. gradient.lock();
  9. var xp:int, yp:int;
  10. for (var i:int = 0; i<pixNum; i++){
  11.     xp = i % size;
  12.     yp = i / size;
  13.     gradient.setPixel(xp, yp, (yp /= 2) <<16 | (255 - yp) <<8 | (xp / 2) );
  14. }
  15. gradient.unlock();
  16.  
  17. // draw an alphaChannel (radial gradient)
  18. var radius:Number = 50;
  19. var diameter:Number = radius * 2;
  20.  
  21. pixNum = diameter * diameter;
  22.  
  23. var brushAlpha = new BitmapData(diameter, diameter, true, 0x00000000);
  24. var dx:int, dy:int;
  25. var ratio:Number = 255 / radius;
  26. var a:int;
  27.  
  28. brushAlpha.lock();
  29. for (i = 0; i<pixNum; i++){
  30.     xp = i % diameter;
  31.     yp = i / diameter;
  32.     dx = xp - radius;
  33.     dy = yp - radius;
  34.     a = int(255 - Math.min(255,Math.sqrt(dx * dx + dy * dy) * ratio));
  35.     brushAlpha.setPixel32(xp, yp, a <<24);
  36. }
  37. brushAlpha.unlock();
  38.  
  39. // create a black canvas
  40. var canvas:BitmapData = new BitmapData(size, size, true, 0xFF000000);
  41. addChild(new Bitmap(canvas));
  42.  
  43. addEventListener(Event.ENTER_FRAME, onLoop);
  44. function onLoop(evt:Event):void {
  45.     // draw the gradient onto the canvas using the alphaChannel (brushAlpha);
  46.     xp = mouseX - radius;
  47.     yp = mouseY - radius;
  48.     canvas.copyPixels(gradient,
  49.                     new Rectangle(xp, yp, diameter, diameter),
  50.                     new Point(xp, yp), brushAlpha, new Point(0,0), true);
  51. }

This demo creates an airbrush that paints one BitmapData onto another. This is achieved by using the alpha related arguments of the BitmapData.copyPixels() function. If your not familiar with these you should take some time to play around with them... they're very powerful.

copyPixels() is the fastest way to draw in flash, so if you need speed, copyPixels() is the way to go. It's much faster than using draw().

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

2 Comments

  1. Posted January 16, 2009 at 1:44 am | Permalink

    Cool Snippet, and I think on line 41 you meant to say canvas instead of layer.

  2. Posted January 16, 2009 at 8:07 am | Permalink

    Thanks. Your right about that Marco…. I fixed line 41 - guess that’s what happens when you decide to change something about the code without testing it :)

Post a Comment

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

*
*