Encyclopedia > Bresenham's line algorithm C code

  Article Content

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);
        }
 }



All Wikipedia text is available under the terms of the GNU Free Documentation License

 
  Search Encyclopedia

Search over one million articles, find something about almost anything!
 
 
  
  Featured Article
Great River, New York

... age of 18 living with them, 70.9% are married couples living together, 7.3% have a female householder with no husband present, and 17.9% are non-families. 13.4% of all ...

 
 
 
This page was created in 60.3 ms