You are on page 1of 5

EXPERIMENT NO 2

Aim: To implement Line Drawing Algorithms:


a) DDA Line Drawing Algorithm
b) Bresenham’s Line Drawing Algorithm

Theory:
DDA Algorithm:
Consider one point of the line as (X0,Y0) and the second point of the line as (X1,Y1).

// calculate dx , dy
dx = X1 - X0;
dy = Y1 - Y0;

// Depending upon absolute value of dx & dy


// choose number of steps to put pixel as
// steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy)
steps = abs(dx) > abs(dy) ? abs(dx0 : abs(dy);

// calculate increment in x & y for each steps


Xinc = dx / (float) steps;
Yinc = dy / (float) steps;

// Put pixel for each step


X = X0;
Y = Y0;
for (int i = 0; i <= steps; i++)
{
putpixel (X,Y,WHITE);
X += Xinc;
Y += Yinc;
}

// C program for DDA line generation


#include<stdio.h>
#include<graphics.h>

//Function for finding absolute value


int abs (int n)
{
return ( (n>0) ? n : ( n * (-1)));
}

//DDA Function for line generation


void DDA(int X0, int Y0, int X1, int Y1)
{
// calculate dx & dy
int dx = X1 - X0;
int dy = Y1 - Y0;
// calculate steps required for generating pixels
int steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy);

// calculate increment in x & y for each steps


float Xinc = dx / (float) steps;
float Yinc = dy / (float) steps;

// Put pixel for each step


float X = X0;
float Y = Y0;
for (int i = 0; i <= steps; i++)
{
putpixel (X,Y,RED); // put pixel at (X,Y)
X += Xinc; // increment in x at each step
Y += Yinc; // increment in y at each step
delay(100); // for visualization of line-
// generation step by step
}
}

// Driver program
int main()
{
int gd = DETECT, gm;

// Initialize graphics function


initgraph (&gd, &gm, "");

int X0 = 2, Y0 = 2, X1 = 14, Y1 = 16;


DDA(2, 2, 14, 16);
return 0;
}

Bresenham’s Algorithm
The points (x1, y1) and (x2, y2) are assumed
not equal and integer valued.
e is assumed to be real.
Let ∆x = x2 − x1
Let ∆y = y2 − y1
Let m =
∆y
∆x
Let j = y1
Let e = m − 1
for i = x1 to x2 − 1
illuminate (i, j)
if(e ≥ 0)
j+=1
e − = 1.0
end if
i+=1
e+=m
next i
finish

# include <stdio.h>
# include <conio.h>
# include <graphics.h>
void main()
{
int dx,dy,x,y,p,x1,y1,x2,y2;
int gd,gm;
clrscr();
printf("\n\n\tEnter the co-ordinates of first point : ");
scanf("%d %d",&x1,&y1);
printf("\n\n\tEnter the co-ordinates of second point : ");
scanf("%d %d",&x2,&y2);
dx = (x2 - x1);
dy = (y2 - y1);
p = 2 * (dy) - (dx);
x = x1;
y = y1;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\tc\\bgi");
putpixel(x,y,WHITE);
while(x <= x2)
{
if(p < 0)
{
x=x+1;
y=y;
p = p + 2 * (dy);
}
else
{
x=x+1;
y=y+1;
p = p + 2 * (dy - dx);
}
putpixel(x,y,WHITE);
}
getch();
closegraph();

You might also like