Main Page | See live article | Alphabetical index

Bresenham's line algorithm C code

An example of Bresenham's line algorithm in C follows. The plotting function is not shown.

void drawline2d(int x0, int y0, int x1, int y1, int color)
{
       int i;
       int steep = 1;
       int sx, sy;  /* step positive or negative (1 or -1) */
       int dx, dy;  /* delta (difference in X and Y between points) */
       int e;

/* * inline swap. On some architectures, the XOR trick may be faster */ int tmpswap; #define SWAP(a,b) tmpswap = a; a = b; b = tmpswap;

/* * optimize for vertical and horizontal lines here */ dx = abs(x1 - x0); sx = ((x1 - x0) > 0) ? 1 : -1; dy = abs(y1 - y0); sy = ((y1 - y0) > 0) ? 1 : -1; if (dy > dx) { steep = 0; SWAP(x0, y0); SWAP(dx, dy); SWAP(sx, sy); } e = (dy << 1) - dx; for (i = 0; i < dx; i++) { if (steep) { plot(x0,y0,color); } else { plot(y0,x0,color); } while (e >= 0) { y0 += sy; e -= (dx << 1); } x0 += sx; e += (dy << 1); } }