Computer Graphics in C,C++

Tuesday, 6 January 2009

Solid line by using Bresenham’s algorithm of any slope

#include "graphics.h"
#include "stdlib.h"
#include "stdio.h"
#include "conio.h"
void main()
{
int gd=DETECT,M;
float dx,dy,x,y,p,m;
float x1,y1,x2,y2;
clrscr();
initgraph(&gd,&M,"");
printf("\n\nEnter the values of x1,y1:");
scanf("%f%f",&x1,&y1);
printf("\n\nEnter the values of x2,y2:");
scanf("%f%f",&x2,&y2);
dx=abs(x2-x1);
dy=abs(y2-y1);
m=dy/dx;
x=x1; //Plot Starting point
y=y1;
putpixel(x,y,6);
if(dx==0) //Vertical Line
{
while(y!=y2)
{
if(y1>y2) y--;
else y++;
putpixel(x,y,3);
}
}

else if(dy==0) //Horizontal Line
{
while(x!=x2)
{
if(x1>x2) x--;
else x++;
putpixel(x,y,3);
}
}
else if(m==1) //Slope 45 deg
{
while(x!=x2)
{
if(x1>x2) x--;
else x++;
if(y1>y2) y--;
else y++;
putpixel(x,y,3);
}
}

else if(m>1) //Slope greater than 1
{
p=dy-2*dx;
while(y!=y2)
{
if(y1>y2) y--;
else y++;
if(p>0)
p=p-2*dx;
else
{
if(x1>x2) x--;
else x++;
p=p+2*(dy-dx);
}
putpixel(x,y,3);
}
}
else //Slope less than 1
{
p=2*dy-dx;
while(x!=x2)
{
if(x1>x2) x--;
else x++;
if(p<0)
p=p+2*dy;
else
{
if(y1>y2) y--;
else y++;
p=p+2*(dy-dx);
}
putpixel(x,y,3);
}
}
getch();
}

No comments:

Post a Comment