var canvas:BitmapData = Bitmap(addChild(new Bitmap(new BitmapData(400,400, false, 0x000000)))).bitmapData;
drawLine(10,10,100,90, 0xFF0000);
drawLine(100,90,60,80, 0xFF0000);
drawLine(100,90,95,60, 0xFF0000);
for (var i:int = 0; i<100; i+=1){
drawLine(i *4, 100 + i, 200, 390);
}
// code ported from here:
// http://www.edepot.com/linebenchmark.html
function drawLine(x1:int, y1:int, x2:int, y2:int, col:uint = 0xFFFFFF){
var x:int, y:int;
var dx:int, dy:int;
var incx:int , incy:int
var balance:int;
if (x2 >= x1){
dx = x2 - x1;
incx = 1;
}else{
dx = x1 - x2;
incx = -1;
}
if (y2 >= y1){
dy = y2 - y1;
incy = 1;
}else{
dy = y1 - y2;
incy = -1;
}
x = x1;
y = y1;
if (dx >= dy){
dy <<= 1;
balance = dy - dx;
dx <<= 1;
while (x != x2){
canvas.setPixel(x, y, col);
if (balance >= 0){
y += incy;
balance -= dx;
}
balance += dy;
x += incx;
}
canvas.setPixel(x, y, col);
}else{
dx <<= 1;
balance = dx - dy;
dy <<= 1;
while (y != y2){
canvas.setPixel(x, y, col);
if (balance >= 0){
x += incx;
balance -= dy;
}
balance += dx;
y += incy;
}
canvas.setPixel(x, y, col);
}
}
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.