DDA Line Drawing Algorithm Using C Programming
In computer graphics, line drawing algorithms are used to generate lines and curves on a computer screen. The DDA (Digital Differential Analyzer) algorithm is a simple and efficient method for drawing lines. This blog post will provide an enhanced and explained version of the DDA line drawing algorithm implemented in C programming language. We will discuss the algorithm, its implementation, and provide a step-by-step explanation of the code.
Prerequisites
Before we dive into the implementation, make sure you have the necessary libraries installed. In this code, we are using the stdio.h, math.h, conio.h, and graphics.h libraries. The graphics.h library is used to create a graphical window for displaying the line.
Implementation
#include<stdio.h>
#include<math.h>
#include<graphics.h>
#define round(val) (int)(val+0.5)
void line_dda(int xa, int ya, int xb, int yb) {
int Dx = xb - xa, Dy = yb - ya, steps, k;
float xin, yin, X = xa, Y = ya;
if (abs(Dx) > abs(Dy))
steps = abs(Dx);
else
steps = abs(Dy);
xin = Dx / (float) steps;
yin = Dy / (float) steps;
putpixel(round(X), round(Y), 6);
for (k = 0; k < steps; k++) {
X = X + xin;
Y = Y + yin;
putpixel(round(X), round(Y), 6);
}
}
int main() {
int gd = DETECT, gm;
int xa, xb, ya, yb;
printf("Enter the two values: ");
scanf("%d%d%d%d", &xa, &ya, &xb, &yb);
initgraph(&gd, &gm, "");
cleardevice();
line_dda(xa, ya, xb, yb);
getch();
closegraph();
return 0;
}Explanation
Let’s go through the code and understand how the DDA line drawing algorithm works.
line_dda function
The line_dda function takes four parameters: xa, ya (starting point) and xb, yb (ending point). It draws the line using the DDA algorithm:
- Calculate
Dx = xb - xaandDy = yb - ya. - Choose the number of steps as the larger of
|Dx|and|Dy|. - Compute per-step increments
xin = Dx / stepsandyin = Dy / steps. - Plot the starting pixel, then update
(X, Y)each step and callputpixel.
main function
- Initialize the graphics system with
initgraph. - Read the two endpoints from the user.
- Clear the screen with
cleardevice. - Call
line_ddato draw the line. - Wait for a key press and close the graphics window.