Thursday, October 25, 2007

Bresenham's Algorithm

Do you want to draw line segments at the speed of light? Just use Bresenham's Algorithm:

void bresenham(x1,y1,x2,y2)
int x1,y2,x2,y2
{
int dx,dy,i,e;
int incx,incy,inc1,inc2;
int x,y;
int locx,locy;

dx = x2-x1;
dy = y2-y1;
if(dx < 0) dx = -dx;
if(dy < 0) dy = -dy;
incx = 1;
if(x2 < x1) incx = -1;
incy = 1;
if(y2 < y1) incy = -1;
x = x1;
y = y1;
if(dx > dy)
locx = x;
locy = y;
set_pixel(locx,locy);
e = 2*dy - dx;
inc1 = 2*(dy-dx);
inc2 = 2*dy;
for(i = 0 ; i < dx ; i++)
{
if(e >= 0)
{
y += incy;
e += inc1;
}
else e += inc2;
x += incx;
locx = x;
locy = y;
set_pixel(locx,locy);
}
}
else
{
locx = x;
locy = y;
set_pixel(locx,locy);
e = 2*dx - dy;
inc1 = 2*(dx-dy);
inc2 = 2*dx;
for(i = 0 ; i < dy ; i++)
{
if(e>=0)
{
x += incx;
e += inc1;
}
else e += inc2;
y = += incy;
locx = x;
locy = y;
set_pixel(locx,locy);
}

}
}

0 Comentarios:

Post a Comment

<< Home