Search This Blog

Bresenham's Line Drawing Algorithm Implementation in C - Generalized Algorithm

Bresenham's line drawing algorithm is an efficient algorithm to draw any line. Unlike DDA algorithm, it uses only integer incremental calculations during the process. This saves much of the CPU time. I am posting a generalized Bresenham's line drawing algorithm (an algorithm that can draw any line in any quadrant with any slope). The main function in this program draws lines of almost all slopes by drawing radial lines for a circle. The entered endpoints of the line are marked in red color. The rest of the line is drawn in the default stroke color in BGI graphics. You can change it by calling setcolor() function.

Output:


Program is given below:

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

int sign(x)
{
if(x>0)
 return 1;
else if(x<0)
 return -1;
else
 return 0;
}


void bres(int x1,int y1, int x2, int y2)
{
int x,y,dx,dy,swap,temp,s1,s2,p,i;

x=x1;
y=y1;
dx=abs(x2-x1);
dy=abs(y2-y1);
s1=sign(x2-x1);
s2=sign(y2-y1);
swap=0;
putpixel(x1,y1,RED);
if(dy>dx)
 {
 temp=dx;
 dx=dy;
 dy=temp;
 swap=1;
 }
p=2*dy-dx;
for(i=0;i<dx;i++)
 {
 putpixel(x,y,getcolor());
 while(p>=0)
  {
  p=p-2*dx;
  if(swap)
   x+=s1;
  else
   y+=s2;
  }
 p=p+2*dy;
 if(swap)
  y+=s2;
 else
  x+=s1;
 }
putpixel(x2,y2,RED);
}

void main()
{
int gd=DETECT,gm;
int x1,y1,x2,y2,theta=0,midx,midy;
initgraph(&gd,&gm,"..\\BGI\\");
midx=getmaxx()/2;
midy=getmaxy()/2;
while(!kbhit())
{
bres(midx,midy,midx+70*sin(3.14f*theta/180),midy+70*cos(3.14f*theta/180));
delay(50);
cleardevice();
theta+=2;
}

}

No comments: