Actionscript:
-
[SWF(width=500, height=500, backgroundColor=0x000000, frameRate=30)]
-
-
// draw an ugly gradient
-
var size:int = 500;
-
var pixNum:int = size * size;
-
var gradient:BitmapData = new BitmapData(size, size, true, 0xFF000000);
-
-
gradient.lock();
-
var xp:int, yp:int;
-
for (var i:int = 0; i<pixNum; i++){
-
xp = i % size;
-
yp = i / size;
-
gradient.setPixel(xp, yp, (yp /= 2) <<16 | (255 - yp) <<8 | (xp / 2) );
-
}
-
gradient.unlock();
-
-
// draw an alphaChannel (radial gradient)
-
var radius:Number = 50;
-
var diameter:Number = radius * 2;
-
-
pixNum = diameter * diameter;
-
-
var brushAlpha = new BitmapData(diameter, diameter, true, 0x00000000);
-
var dx:int, dy:int;
-
var ratio:Number = 255 / radius;
-
var a:int;
-
-
brushAlpha.lock();
-
for (i = 0; i<pixNum; i++){
-
xp = i % diameter;
-
yp = i / diameter;
-
dx = xp - radius;
-
dy = yp - radius;
-
a = int(255 - Math.min(255,Math.sqrt(dx * dx + dy * dy) * ratio));
-
brushAlpha.setPixel32(xp, yp, a <<24);
-
}
-
brushAlpha.unlock();
-
-
// create a black canvas
-
var canvas:BitmapData = new BitmapData(size, size, true, 0xFF000000);
-
addChild(new Bitmap(canvas));
-
-
addEventListener(Event.ENTER_FRAME, onLoop);
-
function onLoop(evt:Event):void {
-
// draw the gradient onto the canvas using the alphaChannel (brushAlpha);
-
xp = mouseX - radius;
-
yp = mouseY - radius;
-
canvas.copyPixels(gradient,
-
new Rectangle(xp, yp, diameter, diameter),
-
new Point(xp, yp), brushAlpha, new Point(0,0), true);
-
}
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().
2 Comments
Cool Snippet, and I think on line 41 you meant to say canvas instead of layer.
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