<<Up     Contents

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 = 0;
        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 = 1;
                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) {
                        y += sy;
                        e -= (dx << 1);
                }
                x += sx;
                e += (dy << 1);
        }
 }

wikipedia.org dumped 2003-03-17 with terodump