Strange BitmapData Drawing Instructions

Actionscript:
  1. // instructions
  2. var ins:Array = [0,
  3. -1, 100, 200, 3, 100, 0, 50, 1, 100, -1, 100, 150, 0, 50,
  4. -1, 160, 200, 0, 50, 3, 50, 2, 50, 3, 50, 0, 50,
  5. -1, 220, 200, 0, 50, 3, 50, 2, 50, -1, 270, 150, 3, 50, 2, 50];
  6.  
  7. var canvas:BitmapData = new BitmapData(400,400,false, 0xCCCCCC);
  8. addChild(new Bitmap(canvas));
  9.  
  10. var index:int = 0;
  11. var penX:int = 0;
  12. var penY:int = 0;
  13.  
  14. read();
  15.  
  16. function read():void{
  17.     var i:int, xp:int, yp:int;
  18.     if (ins[index+1] == -1){
  19.          index++;
  20.         xp = ins[++index];
  21.         yp = ins[++index];
  22.     }else{
  23.         xp = penX;
  24.         yp = penY;
  25.     }
  26.     var dir:int = ins[index];
  27.     var leng:int = ins[++index];
  28.     for (i = 0; i<leng; i++){
  29.         if (dir == 0){
  30.             xp += 1;
  31.         }else if (dir == 1){
  32.             yp += 1;
  33.         }else if (dir == 2){
  34.             xp -= 1;
  35.         }else if (dir == 3){
  36.             yp -= 1;
  37.         }
  38.         canvas.setPixel(xp, yp, 0x000000);
  39.      }
  40.      penX = xp;
  41.      penY = yp;
  42.     if (index <ins.length){
  43.         read();
  44.     }
  45. }

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

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

Post a Comment

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

*
*