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
Islip Terrace, New York

... is 3.51. In the town the population is spread out with 29.5% under the age of 18, 6.7% from 18 to 24, 33.6% from 25 to 44, 20.6% from 45 to 64, and 9.6% who are 65 years ...

 
 
 
This page was created in 25.1 ms