Strange BitmapData Drawing Instructions

// instructions
var ins:Array = [0,
-1, 100, 200, 3, 100, 0, 50, 1, 100, -1, 100, 150, 0, 50,
-1, 160, 200, 0, 50, 3, 50, 2, 50, 3, 50, 0, 50,
-1, 220, 200, 0, 50, 3, 50, 2, 50, -1, 270, 150, 3, 50, 2, 50];

var canvas:BitmapData = new BitmapData(400,400,false, 0xCCCCCC);
addChild(new Bitmap(canvas));

var index:int = 0;
var penX:int = 0;
var penY:int = 0;

read();

function read():void{
	var i:int, xp:int, yp:int;
	if (ins[index+1] == -1){
		 index++;
		xp = ins[++index];
		yp = ins[++index];
	}else{
		xp = penX;
		yp = penY;
	}
	var dir:int = ins[index];
	var leng:int = ins[++index];
	for (i = 0; i<leng; i++){
		if (dir == 0){
			xp += 1;
		}else if (dir == 1){
			yp += 1;
		}else if (dir == 2){
			xp -= 1;
		}else if (dir == 3){
			yp -= 1;
		}
	    canvas.setPixel(xp, yp, 0x000000);
     }
	 penX = xp;
	 penY = yp;
	if (index < ins.length){
		read();
	}
}

I was thinking today about alternative ways to represent drawings and I wrote this snippet while brainstorming. The function read() looks through an array of instructions (ins[]) and draws an image. In this case the letters AS3 are drawn to a Bitmap using setPixel().

The instructions work like this:

The first value of the array is ignored – it can be set to 0, or used to store some other info.
If the next value is a -1, the following two values in the array are used as a sort of moveTo().
This is followed by a direction value 0 = right, 1 = down, 2 = left, 3 = up.
Lastly there is a length value in pixels.

If no -1 is found, the read() function assumes that the value is for a direction.

So to draw a line from (100, 100) to (150, 100) you would write:
[0, -1, 100, 100, 0, 50]

To then draw a line down 50 pixels from the endpoint of the previous line you would add 1 (move down), 50 (length 50)… so you to end up with:
[0, -1, 100, 100, 0, 50, 1, 50]

and so on…

I’m not sure really where I was going with this, but it was fun to write…

Leave a Reply

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