Skip to main content

Bresenham's algorithm for all slopes

Short answer

All-slope Bresenham uses step signs sx and sy. If |Δy| ≤ |Δx|, x is driving axis, p0 = 2Δy − Δx: x += sx; if p<0 p+=2Δy, else y += sy, p+=2Δy−2Δx. If |Δy| > |Δx|, y drives, p0 = 2Δx − Δy: y += sy; if p<0 p+=2Δx, else x += sx, p+=2Δx−2Δy.

Write down Bresenham's line drawing algorithm for drawing a straight line with consideration of all the slope categories.

Bresenham's algorithm works with one coordinate as the unit-step axis (the "driving" axis) and the decision parameter chooses the other coordinate. For a line (x1,y1) to (x2,y2), let Δx = |x2 − x1|, Δy = |y2 − y1|, sx = sign(x2 − x1), sy = sign(y2 − y1).

Slope categories

SlopeDriving axisOther coordinatep0
0 < m < 1x (+1)y increases by 1 or stays2Δy − Δx
m > 1y (+1)x increases by 1 or stays2Δx − Δy
−1 < m < 0x (+1)y decreases by 1 or stays2Δy − Δx
m < −1y (−1)x increases by 1 or stays2Δx − Δy
m = 0xy stayshorizontal line
m = ∞yx staysvertical line

Algorithm

1. Input end points (x1,y1), (x2,y2).
2. Δx = |x2 − x1|, Δy = |y2 − y1|, sx = sign(x2−x1), sy = sign(y2−y1).
3. If Δy ≤ Δx  (|m| ≤ 1): case A, else case B.

Case A (x is the driving axis):
   p = 2Δy − Δx;  x = x1; y = y1; plot (x, y)
   repeat Δx times:
       x = x + sx
       if p < 0:  p = p + 2Δy
       else:      y = y + sy;  p = p + 2Δy − 2Δx
       plot (x, y)

Case B (y is the driving axis):
   p = 2Δx − Δy;  x = x1; y = y1; plot (x, y)
   repeat Δy times:
       y = y + sy
       if p < 0:  p = p + 2Δx
       else:      x = x + sx;  p = p + 2Δx − 2Δy
       plot (x, y)

C code

void bres(int x1,int y1,int x2,int y2){
    int dx=abs(x2-x1), dy=abs(y2-y1);
    int sx=(x2>x1)?1:-1, sy=(y2>y1)?1:-1;
    int x=x1, y=y1, i, p;
    putpixel(x,y,WHITE);
    if(dy<=dx){                       /* |m| <= 1 */
        p=2*dy-dx;
        for(i=0;i<dx;i++){
            x+=sx;
            if(p<0) p+=2*dy;
            else { y+=sy; p+=2*dy-2*dx; }
            putpixel(x,y,WHITE);
        }
    } else {                          /* |m| > 1 */
        p=2*dx-dy;
        for(i=0;i<dy;i++){
            y+=sy;
            if(p<0) p+=2*dx;
            else { x+=sx; p+=2*dx-2*dy; }
            putpixel(x,y,WHITE);
        }
    }
}

The signs sx and sy handle lines drawn in any direction, so all slope categories (positive or negative, less than or greater than 1) are covered.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Graphics chapter 2 questions →