二维图形的裁剪
这是我们做试验时老师编的,发来大家看看给解释解释,俺看的不太明白,源代码如下:#include<graphics.h>
typedef struct{ unsigned all;
unsigned left,right,top,bottom;
}outcode;
typedef struct{ float xmin,xmax,ymin,ymax;
}Rectangle;
Rectangle *rect;
void cohensutherlandlineclip(float x0,float y0,float x1,float y1,Rectangle *rect)
{
void compoutcode(float,float,Rectangle *,outcode *);
int accept,done;
outcode outcode0,outcode1;
outcode *outcodeout;
float x,y;
accept=0;
done=0;
compoutcode(x0,y0,rect,&outcode0);
compoutcode(x1,y1,rect,&outcode1);
do{
if(outcode0.all==0&&outcode1.all==0)
{
accept=1;
done=1;
}
else if(outcode0.all&outcode1.all!=0)
done=1;
else
{
if(outcode0.all!=0)
outcodeout=&outcode0;
else
outcodeout=&outcode1;
if(outcodeout->left)
{
y=y0+(y1-y0)*(rect->xmin-x0)/(x1-x0);
x=(float)rect->xmin;
}
else if(outcodeout->top)
{
x=x0+(x1-x0)*(rect->ymax-y0)/(y1-y0);
y=(float)rect->ymax;
}
else if(outcodeout->right)
{
y=y0+(y1-y0)*(rect->xmax-x0)/(x1-x0);
x=(float)rect->xmax;
}
else if(outcodeout->bottom)
{
x=x0+(x1-x0)*(rect->ymin-x0)/(y1-y0);
y=(float)rect->ymin;
}
if(outcodeout->all==outcode0.all)
{
x0=x;
y0=y;
compoutcode(x0,y0,rect,&outcode0);
}
else
{
x1=x;
y1=y;
compoutcode(x1,y1,rect,&outcode1);
}
}
}while(! done);
if(accept)
line((int)x0,(int)y0,(int)x1,(int)y1);
}
void compoutcode(float x,float y,Rectangle *rect,outcode *outcode)
{
outcode->all=0;
outcode->top=outcode->bottom=0;
if(y>(float)rect->ymax)
{
outcode->top=1;
outcode->all+=1;
}
else if(y<(float)rect->ymin)
{
outcode->bottom=1;
outcode->all+=1;
}
outcode->right=outcode->left=0;
if(x>(float)rect->xmax)
{
outcode->right=1;
outcode->all+=1;
}
else if(x<(float)rect->xmin)
{
outcode->left=1;
outcode->all+=1;
}
}
main()
{
int x0,y0,x1,y1;
int i;
int graphdriver=DETECT;
int graphmode=0;
initgraph(&graphdriver,&graphmode," ");
cleardevice();
x0=450;y0=0;x1=0;y1=450;
rect->xmin=100;
rect->xmax=300;
rect->ymin=100;
rect->ymax=300;
setcolor(2);
rectangle(rect->xmin,rect->ymin,rect->xmax,rect->ymax);
line(x0,y0,x1,y1);
outtextxy(100,400,"press any key to clip!");
i=getch();
clearviewport();
rectangle(rect->xmin,rect->ymin,rect->xmax,rect->ymax);
cohensutherlandlineclip(x0,y0,x1,y1,rect);
outtextxy(100,400,"the result of the clip");
getch();
closegraph();
}
----------------解决方案--------------------------------------------------------