Monday 6 February 2012

Drawing a bitmap

This is something I've found very useful for both prototyping and making final art. The idea is to use vector drawing commands to create a bitmap, or more precisely a BitmapData. This can then be instanced hundreds or even thousands of time very cheaply, much more so than using drawing commands.


The basic technique is as follows.


// create an empty (alpha 0) BitmapData size iW * iH
var data:BitmapData = new BitmapData(iW, iH, false, 0);
// make a shape for drawing
var shape:Shape = new Shape();
// get the Shape's Graphics 
var g:Graphics = shape.graphics;
// draw something

g.beginFill(Col.cBlack);
g.moveTo(iW / 20);
g.lineTo(0, iH);
g.lineTo(iW, iH);
g.lineTo(iW / 20);
// rasterise: draw the Shape to the BitmapData
data.draw(shape);

The lines beginning g. are all drawing commands, with the g dereferenced to make the code more compact (and negligibly more efficient). For illustration this is a very simple example but almost anything can be used, including effects. Filters can be added to the Shape before it is drawn to e.g. smooth the drawing's edges.

For more complex effects multiple passes of drawing can be done, some with Filters and some without. Just use the Graphics clear method to reset the object between drawings.

The other thing to note is that the BitmapData draw method takes a IBitmapDrawable object. This exists solely to describe the things that can be passed to draw, and means any DisplayObject or BitmapData can be drawn into a BitmapData this way. Anything that can be displayed on screen can be drawn, including text, animation frames or the whole game (for e.g. screenshots). A BitmapData can even be drawn into itself, offset with a transform, to produce a motion or reflection.

No comments:

Post a Comment