Thursday, April 14, 2011

C implementation of Bresenham's Line Drawing Algorithm

Hello friends,following is the another program from Computer Graphics subject for Bresenham's Line Drawing Algorithm .Screenshoots shown are taken by running the programs in virtual machine os.

PROGRAM CODE
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<graphics.h>
int round(float x);
void bresenham(int x1,int y1,int x2,int y2,int color);
void main ()
{
clrscr();
int gd=DETECT,gm;
int x1,x2,y1,y2;
printf("\nEnter Starting Point(X1,Y1) :");
scanf("%d%d",&x1,&y1);
printf("\nEnter End Point(X2,Y2) :");
scanf("%d%d",&x2,&y2);
clrscr();
initgraph(&gd,&gm,"C:\\TC\\BGI");

moveto(20,20);
outtext("0");
char xc[80];
int xpos=30,xcc=0;
for(int i=0;i<getmaxx();i++)
{
sprintf(xc,"%d",xcc);
moveto(20+xcc,20);
outtext(xc);
moveto(3,30+xcc);
outtext(xc);
line(xpos,27,xpos,33);
line(27,xpos,33,xpos);
xpos=xpos+50;
xcc=xcc+50;
}
moveto(33+x1,33+y1);
putpixel(x1+30,y1+30,15);
putpixel(x2+30,y2+30,15);
sprintf(xc,"(%d,%d)",x1,y1);
outtext(xc);
moveto(33+x2,33+y2);
sprintf(xc,"(%d,%d)",x2,y2);
outtext(xc);
bresenham(0,30,getmaxx(),30,15);
bresenham(30,0,30,getmaxy(),15);
bresenham(x1+30,y1+30,x2+30,y2+30,15);
moveto(getmaxx()-300,getmaxy()-20);
outtext("Program By 1st Kinecteer");
rectangle(getmaxx()-320,getmaxy()-25,getmaxx()-80,getmaxy()-7);
moveto(getmaxx()-530,getmaxy()-20);
outtext("Bresenham Line Algorithm");
rectangle(getmaxx()-550,getmaxy()-25,getmaxx()-320,getmaxy()-7);
getch();
}
void bresenham(int x1,int y1,int x2,int y2,int color)
{
int x,y,dx,dy,p,i=1,m;
x=x1;
y=y1;
dx=abs(x2-x1);
dy=abs(y2-y1);
if(dy>dx)
{
int t=dx;
dx=dy;
dy=t;
m=1;
}
p=2*dy-dx;
i=1;
do
{
putpixel(x,y,color);
while(p>=0)
{
if(m==1)
x=x+1;
else
y=y+1;
p=p-2*dx;

}
if(m==1)
y=y+1;
else
x=x+1;
p=p+2*dy;
i=i+1;
}
while(i<=dx);
}
OUTPUT






No comments:

Post a Comment