Bresenham's Line Algorithm - The Algorithm

The Algorithm

The common conventions will be used:

  • the top-left is (0,0) such that pixel coordinates increase in the right and down directions (e.g. that the pixel at (7,4) is directly above the pixel at (7,5)), and
  • that the pixel centers have integer coordinates.

The endpoints of the line are the pixels at (x0, y0) and (x1, y1), where the first coordinate of the pair is the column and the second is the row.

The algorithm will be initially presented only for the octant in which the segment goes down and to the right (x0x1 and y0y1), and its horizontal projection is longer than the vertical projection (the line has a negative slope whose absolute value is less than 1.) In this octant, for each column x between and, there is exactly one row y (computed by the algorithm) containing a pixel of the line, while each row between and may contain multiple rasterized pixels.

Bresenham's algorithm chooses the integer y corresponding to the pixel center that is closest to the ideal (fractional) y for the same x; on successive columns y can remain the same or increase by 1. The general equation of the line through the endpoints is given by:

Since we know the column, x, the pixel's row, y, is given by rounding this quantity to the nearest integer:

The slope depends on the endpoint coordinates only and can be precomputed, and the ideal y for successive integer values of x can be computed starting from and repeatedly adding the slope.

In practice, the algorithm can track, instead of possibly large y values, a small error value between −0.5 and 0.5: the vertical distance between the rounded and the exact y values for the current x. Each time x is increased, the error is increased by the slope; if it exceeds 0.5, the rasterization y is increased by 1 (the line continues on the next lower row of the raster) and the error is decremented by 1.0.

In the following pseudocode sample plot(x,y) plots a point and abs returns absolute value:

function line(x0, x1, y0, y1) int deltax := x1 - x0 int deltay := y1 - y0 real error := 0 real deltaerr := abs (deltay / deltax) // Assume deltax != 0 (line is not vertical), // note that this division needs to be done in a way that preserves the fractional part int y := y0 for x from x0 to x1 plot(x,y) error := error + deltaerr if error ≥ 0.5 then y := y + 1 error := error - 1.0

Read more about this topic:  Bresenham's Line Algorithm