Sunday, November 24, 2013

Bresenham's line algorithm

The Bresenham line algorithm is an algorithm which determines which order to form a close approximation to a straight line between two given points. I have here the source code for implementing the algorithm.
#include<iostream.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
#include<math.h>
#include<stdlib.h>
int main()
{
int x1,y1,x2,y2,dy,dx,p;

int gd=DETECT,gm;

initgraph(&gd,&gm,"d:\\borlandc\\bgi");

cout<<"\n ENTER (x1,y1): ";
cin>>x1>>y1;

cout<<"\n ENTER (x2,y2): ";
cin>>x2>>y2;

dx=x2-x1;
dy=y2-y1;



p=(2*dy)-dx;
      int i=0;
/*cout<<"x1="<<x1<<",y1="<<y1<<",P="<<p<<"\n";*/
while(i<=abs(dx))
{


if(p<=0)
{
x1=x1+1;
/*cout<<"x1="<<x1<<",y1="<<y1<<",P="<<p<<"\n";*/
putpixel(x1,y1,GREEN);
p=p+(2*dy);
}
else
{
x1=x1+1;
y1=y1+1;
 /* cout<<"x1="<<x1<<",y1="<<y1<<",P="<<p<<"\n";*/
putpixel(x1,y1,RED);

p=p+(2*dy)-(2*dx);
}
i++;
if(x1==x2&&y1==y2)
{
break;
}
}


getch();
return 0;
}