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
BBC News 24

... extent) in promoting the take-up of digital television. BBC News 24 broadcasts from the BBC News Centre in BBC Television Centre, West London. See also: List of ...

 
 
 
This page was created in 29.1 ms