
#include"conio.h" |
#include"graphics.h" |
#define right 1 |
#define bottom 2 |
#define left 3 |
#define top 4 |
#define N 20 |
void clip_polygon (int Xwmax,int Xwmin,int Ywmax,int Ywmin,int& n,int *x,int *y); |
void clip_single_edge(int edge,int type,int& nin,int *xin,int *yin,int& nout,int *xout,int *yout); |
void test_intersect(int edge,int type,int x1,int y1,int x2, int y2, int& xout,int& yout,int& yes,int& is_in); |
void main() |
{ |
int i; |
int xwmax=400, xwmin=200,ywmax=400,ywmin=200,n=7; |
int x[]={500,300,300,100,351,80,380}; |
int y[]={320,125,450,320,242,420,350}; |
initgraph(640,640); |
setcolor(YELLOW); |
rectangle(200,200,400,400); |
outtextxy(200,20,"按回车键开始剪裁"); |
setcolor(RED); |
for(i=0;i<n;i++) |
{ |
moveto(x[i],y[i]); |
if(i+1!=n) |
lineto(x[i+1],y[i+1]); |
else lineto(x[0],y[0]); |
} |
getch(); |
cleardevice(); |
setcolor(YELLOW); |
rectangle(200,200,400,400); |
clip_polygon(xwmax,xwmin,ywmax,ywmin,n,x,y); |
getch(); |
closegraph(); |
} |
void clip_polygon (int Xwmax,int Xwmin,int Ywmax,int Ywmin,int& n,int *x,int *y) |
{ int x1[N],y1[N],x2[N],y2[N],n1; |
clip_single_edge(Xwmax,right,n,x,y,n1,x1,y1); |
clip_single_edge(Ywmax,bottom,n1,x1,y1,n1,x2,y2); |
clip_single_edge(Xwmin,left,n1,x2,y2,n1,x1,y1); |
clip_single_edge(Ywmin,top,n1,x1,y1,n1,x2,y2); |
setcolor(GREEN); |
for(int i=0;i<n1;i++) |
{ |
moveto(x2[i],y2[i]); |
if(i+1!=n1) |
lineto(x2[i+1],y2[i+1]); |
else lineto(x2[0],y2[0]); |
} |
} |
void clip_single_edge(int edge,int type,int& nin,int *xin,int *yin,int& nout,int *xout,int *yout) |
{ |
int k=0, yes, is_in; |
int x, y, x_intersect, y_intersect; |
x=xin[nin-1];y=yin[nin-1]; |
|
for(int j=0; j<nin; j++) |
{ |
test_intersect(edge, type, x, y,xin[j], yin[j],x_intersect,y_intersect,yes,is_in); |
if(yes) |
{ |
xout[k]=x_intersect; |
yout[k]=y_intersect; |
k++; |
} |
if(is_in) |
{ |
xout[k]=xin[j]; |
yout[k]=yin[j]; |
k++; |
} |
x=xin[j]; |
y=yin[j]; |
} |
nout=k; |
} |
void test_intersect(int edge,int type,int x1,int y1,int x2, int y2, int& xout,int& yout,int& yes,int& is_in) |
{ |
float m; |
is_in=yes=0; |
if(x1!=x2) |
m=(float)((float)y2-(float)y1)/((float)x2-(float)x1); |
switch(type) |
{ |
case right : |
if (x2<edge) |
{ |
is_in=1; |
if(x1>edge) |
yes=1; |
} |
else |
if(x1<=edge) |
yes=1; |
break; |
case bottom: |
if(y2<=edge) |
{ |
is_in=1; |
if(y1>edge) |
yes=1; |
} |
else |
if(y1<=edge) |
yes=1; |
break; |
case left: |
if(x2>=edge) |
{ |
is_in=1; |
if(x1<edge) |
yes=1; |
} |
else |
if(x1>=edge) |
yes=1; |
break; |
case top : |
if(y2>=edge) |
{ |
is_in=1; |
if(y1<edge) |
yes=1; |
} |
else |
if(y1>=edge) |
yes=1; |
default: break; |
} |
if(yes) |
if((type==right) || (type==left)) |
{ |
xout = edge; |
yout=(y1+m*(xout-x1)); |
} |
else |
if(x1==x2) |
{ |
if(type==2&&(y1<=edge||y2<=edge)) |
{xout=x1;yout=edge;} |
if(type==4&&(y1>=edge||y2>=edge)) |
{xout=x1;yout=edge;} |
} |
else |
{ |
yout=edge; xout=x1+(yout-y1)/m; |
} |
} |




by: 发表于:2017-08-10 09:26:12 顶(0) | 踩(0) 回复
??
回复评论