整个程序如下
#include "stdio.h"
#include <math.h>
#include "conio.h"
#include<graphics.h>
typedef struct
{
float x;
float y;
}Vertex;
typedef Vertex Edge[2];
typedef Vertex VertexArray[20];
int Inside(p,ClipBoundary)
Vertex p;
Edge ClipBoundary;
{
if(p.x<ClipBoundary[0].x) return 0;
if(p.x>ClipBoundary[1].x) return 0;
if(p.y<ClipBoundary[0].y) return 0;
if(p.y>ClipBoundary[1].y) return 0;
else
return 1;
}
int xiangjiao(s,p,ClipBoundary)
Vertex s,p;
Edge ClipBoundary;
{
if(ClipBoundary[0].x==ClipBoundary[1].x)
{ if ((s.x<ClipBoundary[0].x)&&(p.x>ClipBoundary[0].x))
return 1;
else if ((p.x<ClipBoundary[0].x)&&(s.x>ClipBoundary[0].x))
return 1;
}
else if (ClipBoundary[0].y==ClipBoundary[1].y)
{if((s.y>ClipBoundary[0].y)&&(p.y<ClipBoundary[0].y))
return 1;
else if ((p.y>ClipBoundary[0].y)&&(s.y<ClipBoundary[0].y))
return 1;
}
return 0;
}
Vertex Intersect(s,p,ClipBoundary)
Vertex s,p;
Edge ClipBoundary;
{
Vertex IntersectPt;
if(ClipBoundary[0].y==ClipBoundary[1].y)
{ IntersectPt.y =ClipBoundary[0].y;
IntersectPt.x =s.x+(ClipBoundary[0].y -s.y)*(p.x - s.x)/(p.y - s.y);
}
if(ClipBoundary[0].x==ClipBoundary[1].x)
{
IntersectPt.x =ClipBoundary[0].x;
IntersectPt.y =s.y+(ClipBoundary[0].x - s.x)*(p.y - s.y)/(p.x - s.x);
}
return IntersectPt;
}
void main()
{
VertexArray InVertexArray,B,C,D,K;
Edge ClipBoundary;
int Inlength,j,i,k,driver,mode;
Vertex s, p,ip,A;
Inlength=5;
driver=DETECT;
mode=0;
initgraph(&driver,&mode,"");
setcolor(15);
InVertexArray[0].x=50;
InVertexArray[0].y=150;
InVertexArray[1].x=200;
InVertexArray[1].y=50;
InVertexArray[2].x=350;
InVertexArray[2].y=150;
InVertexArray[3].x=200;
InVertexArray[3].y=250;
InVertexArray[4].x=50;
InVertexArray[4].y=150;
for (i=1;i<=4;i++)
{
switch(i){
case 1:ClipBoundary[0].x=100;
ClipBoundary[0].y=100;
ClipBoundary[1].x=100;
ClipBoundary[1].y=200;
break;
case 2: ClipBoundary[0].x=100;
ClipBoundary[0].y=100;
ClipBoundary[1].x=300;
ClipBoundary[1].y=100;break;
case 3: ClipBoundary[0].x=300;
ClipBoundary[0].y=100;
ClipBoundary[1].x=300;
ClipBoundary[1].y=200;break;
case 4: ClipBoundary[0].x=300;
ClipBoundary[0].y=200;
ClipBoundary[1].x=100;
ClipBoundary[1].y=200;break;
default: break;
}
for(j =1;j<Inlength;j++)
{ p=InVertexArray[j];
s=InVertexArray[j-1];
if(xiangjiao(s,p, ClipBoundary))
{
B[j]=Intersect(s, p, ClipBoundary);
printf("%5f\n",B[j].x);
printf("%5f\n",B[j].y);
InVertexArray[j]=B[j];
}
}
}
getch();
restorecrtmode();
}