Bresenham line

Actionscript:
  1. var canvas:BitmapData = Bitmap(addChild(new Bitmap(new BitmapData(400,400, false, 0x000000)))).bitmapData;
  2.  
  3. drawLine(10,10,100,90, 0xFF0000);
  4. drawLine(100,90,60,80, 0xFF0000);
  5. drawLine(100,90,95,60, 0xFF0000);
  6.    
  7. for (var i:int = 0; i<100; i+=1){
  8.     drawLine(i *4, 100 + i, 200, 390);
  9. }
  10. // code ported from here:
  11. // http://www.edepot.com/linebenchmark.html
  12. function drawLine(x1:int, y1:int, x2:int, y2:int, col:uint = 0xFFFFFF){
  13.     var x:int, y:int;
  14.     var dx:int, dy:int;
  15.     var incx:int , incy:int
  16.     var balance:int;
  17.  
  18.     if (x2>= x1){
  19.         dx = x2 - x1;
  20.         incx = 1;
  21.     }else{
  22.         dx = x1 - x2;
  23.         incx = -1;
  24.     }
  25.  
  26.     if (y2>= y1){
  27.         dy = y2 - y1;
  28.         incy = 1;
  29.     }else{
  30.         dy = y1 - y2;
  31.         incy = -1;
  32.     }
  33.  
  34.     x = x1;
  35.     y = y1;
  36.  
  37.     if (dx>= dy){
  38.         dy <<= 1;
  39.         balance = dy - dx;
  40.         dx <<= 1;
  41.  
  42.         while (x != x2){
  43.             canvas.setPixel(x, y, col);
  44.             if (balance>= 0){
  45.                 y += incy;
  46.                 balance -= dx;
  47.             }
  48.             balance += dy;
  49.             x += incx;
  50.         }
  51.         canvas.setPixel(x, y, col);
  52.     }else{
  53.         dx <<= 1;
  54.         balance = dx - dy;
  55.         dy <<= 1;
  56.  
  57.         while (y != y2){
  58.             canvas.setPixel(x, y, col);
  59.             if (balance>= 0){
  60.                 x += incx;
  61.                 balance -= dy;
  62.             }
  63.             balance += dx;
  64.             y += incy;
  65.         }
  66.         canvas.setPixel(x, y, col);
  67.     }
  68. }

This snippet shows Brensenham's line drawing algorithm. I ported this implementation from here... all the line algorithms in that link are easy to port to actionscript. I've messed with them all at some point.

Tomorrow I'm going to post a super slow line drawing algorithm... so I figured I'd post a fast line drawing algorithm today.

This entry was posted in BitmapData, graphics algorithms, 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 *

*
*