Saturday 17 September 2011

BRESENHAM’S LINE ALGORITHM


BRESENHAM’S LINE ALGORITHM
Aim:
     To write a C++ Program to draw a line using Bresenhams algorithm.


Algorithm:
Start the program .
Initialize the variables.
Call the initgraph() function
Get the values for left and right end points for drawing a line..
Calculate the distance to be traveled by the line.
Put the pixels in the given color to draw the line.
Display the output.
stop the program


PROGRAM

#include<stdio.h>
#include<conio.h>
#include<iostream.h>
#include<math.h>
#include<graphics.h>
#include<stdlib.h>
void main()
{
int gd=DETECT,gm,x0,y0,x1,y1,p,dx,dy,i,x2,y2,ec;
ec=graphresult();
if(ec!=grOk)
{
cout<<"Graphics error:%s\n",grapherrormsg(ec);
cout<<"press any key to halt";
getch();
exit(1);
}
initgraph(&gd,&gm,"");
cout<<"enter left end pt";
cin>>x0>>y0;
cout<<"Enter right end pts";
cin>>x1>>y1;
cleardevice();
dx=abs(x1-x0);
dy=(y1-y0);
if(dx<dy)
{
y2=dx;
dx=dy;
dy=y2;
x2=x0;
y2=y0;
}
else
{
x2=y0;
y2=x0;
}
p=2*dx*dy;
putpixel(x2,y2,RED);
for(i=0;i<=x0;i++)

{
if(p<0)
{
y2=y2+1;
p=p+2*dy;
}
else
{
x1++;
p=p+2*dy-2*dx;
}
putpixel(x1,y1,RED);
}
setbkcolor(GREEN);
getch();
return;
}
Output:
Enter the left and right end points:
0 0
10 10

0 comments:

Post a Comment