Unveiling Design Patterns: A Visual Guide with UML Diagrams
Digital Differential Analyzer Line Drawing Algorithm
1. Computer Graphics
1 of 5
Lesson 1: Digital Differential Analyzer Line Drawing Algorithm
Author: Kasun Ranga Wijeweera
Email: krw19870829@gmail.com
Date: 2020 June 16
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
Pseudocode of Digital Differential Analyzer Line Drawing Algorithm
VOID draw (INTEGER x1, INTEGER y1, INTEGER x2, INTEGER y2)
{
INTEGER dx, dy, steps, k;
REAL xInc, yInc, x, y;
dx = x2 – x1;
dy = y2 – y1;
x = x1;
y = y1;
IF (|dx| > |dy|)
steps = |dx|
ELSE
steps = |dy|
END IF
xInc = dx/steps;
yInc = dy/steps;
SET_PIXEL (ROUND (x), ROUND (y));
FOR (k = 1 TO steps)
x = x + xInc;
y = y + yInc;
SET_PIXEL (ROUND (x), ROUND (y));
END FOR
}
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
draw (2, 3, 7, 5);
dx = 7 – 2 = 5;
dy = 5 – 3 = 2;
x = 2;
y = 3;
5 > 2 TRUE;
steps = 5;
xInc = 5/5 = 1;
yInc = 2/5 = 0.4;
SET_PIXEL (2, 3);
5
4
3
2 3 4 5 6 7
4. Computer Graphics
4 of 5
k = 1
x = 2 + 1 = 3;
y = 3 + 0.4 = 3.4;
SET_PIXEL (3, 3);
5
4
3
2 3 4 5 6 7
k = 2
x = 3 + 1 = 4;
y = 3.4 + 0.4 = 3.8;
SET_PIXEL (4, 4);
5
4
3
2 3 4 5 6 7
k = 3
x = 4 + 1 = 5;
y = 3.8 + 0.4 = 4.2;
SET_PIXEL (5, 4);
5
4
3
2 3 4 5 6 7
5. Computer Graphics
5 of 5
k = 4
x = 5 + 1 = 6;
y = 4.2 + 0.4 = 4.6;
SET_PIXEL (6, 5);
5
4
3
2 3 4 5 6 7
k = 5
x = 6 + 1 = 7;
y = 4.6 + 0.4 = 5;
SET_PIXEL (7, 5);
5
4
3
2 3 4 5 6 7