Computer graphics programming can be written in computer languages like C, C++, java and many more.
DDA line drawing algorithm:
DDA (
Digital Differential Analyzer ) Algorithm is scan conversion of line. It
accepts end points of line A(x1,y1) and B(x2,y2) , finds intermediate pixel
location and display on display device.
we know
line equation y=mx+c where m is slope and c is y-intercept as constant.
slope
m=(y2-y1)/(x2-x1)
= dy/dx where
dx=(x2-x1)
and dy=(y2-y1)
we can
calculate dy if we know dx as dy=m.dx and
we can calculate dx if we know dy as dx=dy/m.
from above
equation we can say if dx=1 then dy=m and if dy=1 then dx=1/m.
DDA
algorithm increments by unit value in one coordinate and second coordinate can
be calculated. Unit increment is based on slope. if abs(slope) <1 then increment
by one in x coordinate and y coordinate increment can be calculated by yinc=m.
xinc=1,yinc=m
if abs(slope)>1 then increment by one in y
coordinate and calculate x coordinate increment as xinc=1/m.
yinc=1,xinc=1/m
using
increment factor all intermediate values can be calculated as
xnext=xcurrent+xinc
ynext=ycurrent+yinc
this prcess
is recurssive till we reach last
coordinate of line (x2,y2).
Algorithm Steps:
1.Accept input (x1,y1) and (x2,y2)
as end points of Line
2. Calculate dx=(x2-x1) and dy=(y2-y1).
3. If abs(dx)>=abs(dy)
length=dx
else
length=dy
4.
Calculate xinc=dx/length and yinc=dy/length.
5. Plot
first pixel (x1,y1) .
6.
Calculate xnext=xcurrent+xinc and ynext=ycurrent+yinc and plot(xnext, ynext).
7. Repeat
step 6 ,length times.
8. Stop DDA line drawing algorithm Implementation in C-Language:
Program:
#include<stdio.h>
#include<graphics.h>
#include<math.h>
#include<conio.h>
void main()
{
int gd=DETECT,gm;
int i,len;
float x1,y1,x2,y2,dx,dy,xinc,yinc;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
printf("Enter x1");
scanf("%f",&x1);
printf("Enter y1");
scanf("%f",&y1);
printf("Enter x2");
scanf("%f",&x2);
printf("Enter y2");
scanf("%f",&y2);
dx=(x2-x1);
dy=(y2-y1);
if(abs(dx)>=abs(dy))
{
len=dx;
}
else
{
len=dy;
}
xinc=dx/len;
yinc=dy/len;
putpixel(x1,y1,4);
for(i=1;i<=len;i++)
{
x1=x1+xinc;
y1=y1+yinc;
putpixel(x1,y1,4);
}
getch();
}
Output: