Draw Polygon using Graphics


#include<stdio.h>
#include<conio.h>
#include<dos.h>
#include<graphics.h>
void disppolygon(float[],float[],int);
void displaywindow(float,float,float,float);

void main()
{
float xwmin,xwmax,ywmin,ywmax;
int gd,gm;
int v,j,i;
float x1[20],y1[20],m;
float x[10],y[10];
clrscr();
gm=gd=DETECT;
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
printf("Enter the window coordinates xwmin & ywmin:");
scanf("%f%f",&xwmin,&ywmin);
printf("\nEnter the window coordinates xwmax & ywmax:");
scanf("%f%f",&xwmax,&ywmax);
printf("\nEnter the number of vertices of polygon:");
scanf("%d",&v);
for(i=0;i<v;i++)
{
printf("\nEnter the x & y points vertex %d",i+1);
scanf("%f %f",&x[i],&y[i]);
}
x[v]=x[0];
y[v]=y[0];
cleardevice(); setcolor(15);
disppolygon(x,y,v);
displaywindow(xwmin,ywmax,xwmax,ywmin);
getch();
//left clipping
j=0;
for(i=0;i<v;i++)
{
if(x[i]<xwmin && x[i+1]>=xwmin)
{
if(x[i+1]-x[i]!=0)
{
y1[j]=(y[i+1]-y[i])/(x[i+1]-x[i])*(xwmin-x[i])+y[i];
}
else
{
y1[j]=y[i];
}
x1[j]=xwmin;
j++;
x1[j]=x[i+1];
y1[j]=y[i+1];
j++;
}
if(x[i]>xwmin && x[i+1]>=xwmin)
{
x1[j]=x[i+1];
y1[j]=y[i+1];
j++;
}
if(x[i]>xwmin && x[i+1]<=xwmin)
{
if(x[i+1]-x[i]!=0)
{
y1[j]=(y[i+1]-y[i])/(x[i+1]-x[i])*(xwmin-x[i])+y[i];
}
else
y1[j]=y[i];
x1[j]=xwmin;
j++;
/*x1[j]=x[i+1];
y1[j]=y[i+1];
j++;*/
}
}
cleardevice();
setcolor(15);
disppolygon(x1,y1,v);
displaywindow(xwmin,ywmin,xwmax,ywmax);
getch();
}

void disppolygon(float x[],float y[],int v)
{
int i;
x[v]=x[0];
y[v]=y[0];
for(i=0;i<v;i++)
{
line(x[i],y[i],x[i+1],y[i+1]);
}
}

void displaywindow(float xwmin,float ywmin,float xwmax,float ywmax)
{
rectangle(xwmin,ywmin,xwmax,ywmax);
}
Previous Post Next Post