1. Computer Graphics
1 of 5
Lesson 2: Bresenham Line Drawing Algorithm
Author: Kasun Ranga Wijeweera
Email: krw19870829@gmail.com
Date: 2020 June 19
The screen of a computer is a rectangular grid. A cell in the grid is
called a “pixel”. An example is given below that has 20 × 20 pixels.
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
2. Computer Graphics
2 of 5
Bresenham Line Drawing Algorithm in Step Form for |m| < 1
Note: Let (x1, y1) is the left endpoint, (x2, y2) is the right endpoint,
and m is the gradient of the line segment.
1) Set k = 0.
2) Fill pixel (x[k], y[k]); i.e., fill pixel (x1, y1).
3) Compute p [k] = 2 * dy – dx where dx = x2 – x1 and dy = y2 – y1.
4) If p [k] < 0, fill pixel (x [k] + 1, y [k]) and p [k + 1] = p [k] + 2 * dy.
Otherwise, fill pixel (x [k] + 1, y [k] + 1) and p [k + 1] = p [k] + 2 *
dy – 2 * dx.
5) Set k = k + 1 and go to step 4 if k < dx.
3. Computer Graphics
3 of 5
Example
Demonstrate drawing a line segment from (2, 3) to (7, 5).
Answer:
5
4
3
2 3 4 5 6 7
k = 0;
SET_PIXEL (2, 3);
5
4
3
2 3 4 5 6 7
dx = 7 – 2 = 5;
dy = 5 – 3 = 2;
p [0] = 2 * 2 – 5 = -1;
p [0] < 0;
SET_PIXEL (3, 3);
5
4
3
2 3 4 5 6 7
4. Computer Graphics
4 of 5
p [1] = -1 + 2 (2) = 3;
k = 1 < 5;
p [1] ≥ 0;
SET_PIXEL (4, 4);
5
4
3
2 3 4 5 6 7
p [2] = 3 + 2 (2) – 2 (5) = -3;
k = 2 < 5;
p [2] < 0;
SET_PIXEL (5, 4);
5
4
3
2 3 4 5 6 7
p [3] = -3 + 2 (2) = 1;
k = 3 < 5;
5. Computer Graphics
5 of 5
p [3] ≥ 0;
SET_PIXEL (6, 5);
5
4
3
2 3 4 5 6 7
p [4] = 1 + 2 (2) – 2 (5) = -5;
k = 4 < 5;
p [4] < 0;
SET_PIXEL (7, 5);
5
4
3
2 3 4 5 6 7
p [5] = -5 + 2 (2) = -1;
k = 5 ≥ 5.