Bresenham Line Drawing Algorithm

suggest change

Bresenham's line algorithm generates the raster points that approximate a straight line. It uses integer arithmetic and can be adapted to rasterize circles and other curves.

In Bresenham line drawing algorithm:

For Slope |m|<1: Either value of x is increased OR both x and y is increased using decision parameter.

For Slope |m|>1: Either value of y is increased OR both x and y is increased using decision parameter.

Algorithm for slope |m|<1:

  1. Input two end points (x1,y1) and (x2,y2) of the line.
  2. Plot the first point (x1,y1).
  3. Calculate Delx =| x2 – x1 | Dely = | y2 – y1 |
  4. Obtain the initial decision parameter as P = 2 * dely – delx
  5. For I = 0 to delx in step of 1
If p < 0 then<br>
           X1 = x1 + 1<br>
           Pot(x1,y1)<br>
           P = p+ 2*dely<br><br>

Else

X1 = x1 + 1<br>
Y1 = y1 + 1<br>
Plot(x1,y1)<br>
P = p + 2*dely – 2 * delx<br><br>

End if End for 6. END

Source Code:

#include <stdlib.h>

typedef void (*plot_fn)(int x, int y, void *context);

// Generates both endpoints and works for every direction and slope.
void draw_line(int x0, int y0, int x1, int y1,
               plot_fn plot, void *context) {
    const int dx = abs(x1 - x0);
    const int step_x = x0 < x1 ? 1 : -1;
    const int dy = -abs(y1 - y0);
    const int step_y = y0 < y1 ? 1 : -1;
    int error = dx + dy;

    for (;;) {
        plot(x0, y0, context);
        if (x0 == x1 && y0 == y1) return;

        const int doubled_error = 2 * error;
        if (doubled_error >= dy) {
            error += dy;
            x0 += step_x;
        }
        if (doubled_error <= dx) {
            error += dx;
            y0 += step_y;
        }
    }
}

The callback keeps the algorithm independent of any particular graphics library. A caller can supply a function that colors a pixel in an image, updates a framebuffer, or records the generated coordinates.

Algorithm for slope |m|>1:

  1. Input two end points (x1,y1) and (x2,y2) of the line.
  2. Plot the first point (x1,y1).
  3. Calculate
Delx =| x2 – x1 |<br>
Dely = | y2 – y1 |
  1. Obtain the initial decision parameter as P = 2 * delx – dely
  2. For I = 0 to dely in step of 1 If p < 0 then
y1 = y1 + 1<br>
Pot(x1,y1)<br>
P = p+ 2*delx<br><br>

Else

X1 = x1 + 1<br>
Y1 = y1 + 1<br>
Plot(x1,y1)<br>
P = p + 2*delx – 2 * dely<br><br>

End if End for 6) END

The unified implementation above handles this case too. Keeping a single all-octants implementation avoids the nonportable graphics.h/conio.h APIs and fixes the common edge cases of decreasing coordinates, negative slopes, and vertical lines.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents