中点画直线算法 (11)
/* Cohen-Sutherland Ö?Ïß?Ã?ôËã?? */
#include "graphics.h"
#include "stdio.h"
#include "conio.h"
int left=100, right=200, bottom=180, top=50; // ???Ú?ß?ò int a[4], b[4], c[4];
main()
{
void line_clip();
void getcode(int x, int y, int d[4]); // ??Òå?ñµÃ?˵ãµÄ?úÂëº?Êý
int gd=DETECT, gm;
int stratx, straty, endx, endy, left, top, right, bottom;
int a1, b1, a2, b2, x, y;
char ch;
initgraph(&gd, &gm, "D:\\TC");
a1=60; b1=40;
a2=170; b2=300;
stratx=100; straty=50; // Ö?ÏßµÄÆðµã
endx=200; endy=180; // Ö?ÏßµÄÖÕµã
getcode(a1, b1, a);
getcode(a2, b2, b);
printf("\n\n\n\n\n\n\n\n\n\n\t\t\t the code of point P1 is:\n");
printf("\t\t\t a[0]=%d, a[1]=%d, a[2]=%d, a[3]=%d\n\n", a[0], a[1], a[2], a[3]);
printf("\t\t\t the code of point P2 is:\n");
printf("\t\t\t b[0]=%d, b[1]=%d, b[2]=%d, b[3]=%d", b[0], b[1], b[2], b[3]);
setcolor(15);
rectangle(stratx, straty, endx, endy); // Éè??Ò??ØÐÎ???Ú
line(a1, b1, a2, b2);
getch();
line_clip(a1, b1, a2, b2, stratx, straty, endx, endy); // ?????ÚÖ?ÍâµÄÏß?Î?Ã?ôµô
setcolor(15);
setlinestyle(0, 0, 1);
rectangle(stratx, straty, endx, endy);
getch();
closegraph();
}
/*********?Ã?ôº?Êý************/
void line_clip(int x1, int y1, int x2, int y2, int left,int top,int
right, int bottom)
{
void getcode(int x, int y, int d[4]);
int i, x11, y11; // ??Òå??µã×ø?ê
int aa=1;
getcode(x1, y1, a);
getcode(x2, y2, b);
// 1?º?Ã?ôÑ,???ªÊ?
while(aa!=0){
if((a[0]+a[1]+a[2]+a[3]==0)&&(b[0]+b[1]+b[2]+b[3]==0)){ //
Ïß?ÎÍêÈ??É?û
aa=0;
return;
}
else
if((a[0]&&b[0])+(a[1]&&b[1])+(a[2]&&b[2])+(a[3]&&b[3])!=0){ //
Ïß?ÎÍêÈ????É?û
setcolor(0);
setwritemode(0); // ÉèÖÃ?,ÏßµÄÊä?öÄ?Ê?Ϊ???Ç??Ê?
line(x1, y1, x2, y2);
aa=0;
return;
}
//
2?ºÏß?Î?È??ÍêÈ??É?û??Ò???ÍêÈ????É?û????Óë?ßÓÐ??µãµÄÏß?εÄ?Ã?ô??Àí
else{
if(a[0]+a[1]+a[2]+a[3]==0){ // Ñ?ÕÒ???É?ûµã
for(i=0; i<4; i++)
c[i]=b[i]; // x2,y2Ϊ???É?ûµã
}
else{
for(i=0; i<4; i++)
c[i]=a[i]; // x1,y1Ϊ???É?ûµã
}
// 3?ºÖ?ÏßÓë???Ú?ß×?Çó??ÔËËã??Çó?ö??µã??Öµ?øx11??y11
if(c[0]==1){
x11=left;
y11=(int)((y2-y1)*(left-x1)/(x2-x1)+y1);
}
else if(c[1]==1){
x11=right;
y11=(int)((y2-y1)*(right-x1)/(x2-x1)+y1);
}
else if(c[2]==1){
x11=(int)((x2-x1)*(bottom-y1)/(y2-y1)+x1);
y11=bottom;
}
else if(c[3]==1){
x11=(int)((x2-x1)*(top-y1)/(y2-y1)+x1);
y11=top;
} // 3?ºÇó??ÔËËã?áÊø
if((c[0]==a[0])&&(c[1]==a[1])&&(c[2]==a[2])&&(c[3]==a[3])){
setcolor(0);
setlinestyle(0, 0, 3);
setwritemode(0);
line(x1, y1, x11, y11);
x1=x11; y1=y11;
getcode(x11, y11, a);
getch();
}
else
if((c[0]==b[0])&&(c[1]==b[1])&&(c[2]==b[2])&&(c[3]==b[3])){
setcolor(0);
setlinestyle(0, 0, 3);
setwritemode(0);
line(x2, y2, x11, y11);
x2=x11; y2=y11;
getcode(x11, y11, b);
getch();
}
} // 2?ºÓë?ßÓÐ??µãµÄÏß?Î?Ã?ô??Àí?áÊø
} // 1?º?Ã?ôÑ,???áÊø
}
void getcode(int x, int y, int d[4]) {
d[0]=0; d[1]=0; d[2]=0; d[3]=0;
if(xright) d[1]=1;
if(y>bottom) d[2]=1;
if(y