Cglab
Cglab
Objective:
To use DDA algorithm to draw a line between given points.
Theory:
In computer graphics, a line segment between two points (x1,y1) and (x2,y2) cannot be directly
drawn because the display screen consists of discrete pixels arranged in a grid. To render the
line, intermediate points must be calculated, and the corresponding pixels are colored to
approximate the line segment.
The Digital Differential Analyzer (DDA) algorithm is a simple and efficient method used to
compute these intermediate points. The algorithm works by incrementing either the x-
coordinate or the y-coordinate in small, fixed steps, based on the slope of the line (m). The
other coordinate is calculated accordingly, ensuring that each step results in a point as close as
possible to the actual line. The output screen in computer graphics is treated as a coordinate
system, where the top-left corner is (0,0). Moving to the right increases the x-coordinate, and
moving down increases the y-coordinate. The function putpixel(x, y, K) is used in
programming to plot a pixel at the specified coordinate (x,y) with a color K.
By applying the DDA algorithm, we can efficiently generate and display a line segment pixel
by pixel between two given points. This algorithm ensures smooth and precise rendering of the
line in a graphical environment.
DDA Algorithm:
Step 1: Start
Step 2: Take the coordinates of initial point (x1,y1) and the final point (x2,y2).
Step 3: Find the difference between the points by using the formula:
dx = x2-x1;
dy = y2-y1;
Step 4: Compare the absolute value of the differences to get the number of steps.
If abs(dx) > abs(dy)
steps = dx;
Else
steps = dy;
Step 5: Calculate the increment of x1 and y1 in each step.
dx = dx/steps;
dy = dy/steps;
Step 6: Put pixel in (x1,y1).
Step 7: Repeat step 5 while adding dx to x and dy to y until steps reaches zero.
while (steps != 0)
putpixel(x1,y1,K);
x1 = x1+dx;
y1 = y1+dy;
end while
Step 8: Stop
Source code:
The code for the program is given below:
#include<iostream> if (dx > dy)
#include<math.h> else
int x1, y1, x2, y2, dx, dy, steps, i; float yn = y1;
cout << "Enter ending point(x2, y2): "; putpixel(round(xn), round(yn), BLACK);
dx = abs(x2 - x1); }
return 0;
Output:
The output of the asked program is given below:
Conclusion:
Thus, as demonstrated in the program above, we can draw a line between two points by plotting
individual pixels using the Digital Differential Analyzer (DDA) algorithm with the functions
provided in the graphics.h header file. For the input points (x1,y1)=(50,100) and
(x2,y2)=(200,400), the program successfully generated a smooth line on the graphical output
screen.