Bresenham’s Circle and setVector()

var canvasSize:int = 400;
var canvas:BitmapData = new BitmapData(canvasSize, canvasSize, false, 0xFFFFFF);
addChild(new Bitmap(canvas));
var size:int = canvas.width * canvas.height;
var pixels:Vector.<uint> = canvas.getVector(canvas.rect);

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	 for (var i:int = 0; i<500; i++){
	  fillCircle(int(Math.random() * canvasSize),
					  int(Math.random() * canvasSize),
					  int(Math.random() * 5 + 3),
					  uint(Math.random() * 0xFFFF));
	 }
	 canvas.lock();
	 canvas.setVector(canvas.rect, pixels);
	 canvas.unlock();
}

function fillCircle(xp:int,yp:int, radius:int, col:uint = 0x000000):void {
	var xoff:int =0;
	var yoff:int = radius;
	var balance:int = -radius;
	while (xoff <= yoff) {
		 var p0:int = xp - xoff;
		 var p1:int = xp - yoff;
		 var w0:int = xoff + xoff;
		 var w1:int = yoff + yoff;
		 hLine(p0, yp + yoff, w0, col);
		 hLine(p0, yp - yoff, w0, col);
		 hLine(p1, yp + xoff, w1, col);
		 hLine(p1, yp - xoff, w1, col);
		if ((balance += xoff++ + xoff)>= 0) {
			balance-=--yoff+yoff;
		}
	}
}
function hLine(xp:int, yp:int, w:int, col:uint):void {
	var index:int = xp + yp * canvasSize;
	for (var i:int = 0; i <w; i++){
		index++;
		if (index > -1 && index < size){
		  pixels[index] = col;
		}
	}
}

In the past I’ve posted examples of Bresenham’s Circle (here and here). Both of those examples make use of setPixel(). Today’s snippet demos a version of Bresenham’s Circle that works with setVector().

Leave a Reply

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