Bresenham Circle No Multiplication

Actionscript:
  1. var canvas:BitmapData = new BitmapData(400, 400, false, 0xCCCCCC);
  2. addChild(new Bitmap(canvas));
  3.  
  4. drawCircle(200,100, 50);
  5.  
  6. // y, y radius, color
  7. function drawCircle(xp:Number,yp:Number, radius:Number, col:uint =0x000000):void {
  8.     var balance:int;
  9.     var xoff:int;
  10.     var yoff:int;
  11.     xoff=0;
  12.     yoff=radius;
  13.     balance=- radius;
  14.  
  15.     while (xoff <= yoff) {
  16.         canvas.setPixel(xp+xoff, yp+yoff, col);
  17.         canvas.setPixel(xp-xoff, yp+yoff, col);
  18.         canvas.setPixel(xp-xoff, yp-yoff, col);
  19.         canvas.setPixel(xp+xoff, yp-yoff, col);
  20.         canvas.setPixel(xp+yoff, yp+xoff, col);
  21.         canvas.setPixel(xp-yoff, yp+xoff, col);
  22.         canvas.setPixel(xp-yoff, yp-xoff, col);
  23.         canvas.setPixel(xp+yoff, yp-xoff, col);
  24.  
  25.         if ((balance += xoff++ + xoff)>= 0) {
  26.             balance-=--yoff+yoff;
  27.         }
  28.     }
  29. }

The above demos a circle drawing algorithm. This will draw an outlined circle with no fill. This implementation doesn't use multiplication.

Using setPixel to draw primitive shapes can be a good learning experience. I found this basic implementation of the Bresenham Circle algorithm a few years back and lost the original link.... I dug around for a good hour trying to find the original but to no avail. So if someone recognizes this interesting implementation .... let me know :)

The original code was written in java I think.

If your curious. The standard implementation I keep finding online looks something like this:

Actionscript:
  1. // ported from http://www.codeuu.com/Bresenham_Circle
  2. function drawCircle(cx:Number, cy:Number, r:Number, col:uint):void{
  3.     var xp:int  = 0, yp:int= r ;
  4.     var d:int = 3 - (2 * r);
  5.    
  6.     while(xp <= yp){
  7.        
  8.         canvas.setPixel(cx+xp,cy+yp,col);
  9.         canvas.setPixel(cx+yp,cy+xp,col);
  10.         canvas.setPixel(cx-xp,cy+yp,col);
  11.         canvas.setPixel(cx+yp,cy-xp,col);
  12.         canvas.setPixel(cx-xp,cy-yp,col);
  13.         canvas.setPixel(cx-yp,cy-xp,col);
  14.         canvas.setPixel(cx+xp,cy-yp,col);
  15.         canvas.setPixel(cx-yp,cy+xp,col);
  16.        
  17.         if (d<0){
  18.             d += (4*xp)+6;
  19.         }else{
  20.             d += (4*(xp-yp))+10;
  21.             yp -= 1;
  22.         }
  23.         xp++;
  24.     }
  25.    
  26. }

I did a few speed tests against the first one that doesn't make use of multiplication and it is only ever so slightly faster....

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

*
*