#include #include #include #include #define TOP 8 #define BOTTOM 4 #define LEFT 2 #define RIGHT 1 #define ACC(c1,c2) ((c1 == 0) && (c2 == 0)) #define REJ(c1,c2) ((c1 & c2) != 0) void swap(int *c1, int *c2) { int t; t=*c1; *c1=*c2; *c2=t; } int getcode (int x, int y) { int code; if (y > 479) code=BOTTOM; else if (y < 0) code=TOP; else code=0; if (x > 639) code |= RIGHT; else if (x < 0) code |= LEFT; return code; } void main() { int Driver; /* The Graphics device driver */ int Mode; /* The Graphics mode value */ struct point { int x,y; } p1,p2,p3,p4; int c2,c1; float x,y; printf("give me the 1st line point--->"); scanf("%d %d",&p1.x,&p1.y); printf("give me the 2nd line point--->"); scanf("%d %d",&p2.x,&p2.y); getche(); p3=p1; p4=p2; c1=getcode(p1.x,p1.y); c2=getcode(p2.x,p2.y); if (REJ(c1,c2)) printf("line cannot draw !!!\n"); else { printf("(%d,%d) --> code=%d\n",p1.x,p1.y,c1); printf("(%d,%d) --> code=%d\n",p2.x,p2.y,c2); getche(); x=p1.x; y=p1.y; while (!ACC(c1,c2)) { if (c1 == 0) { swap(&c1,&c2); swap(&p1.x,&p2.x); swap(&p1.y,&p2.y); x=p1.x; y=p1.y; } else if (c1 & TOP) { x+=(p2.x-p1.x)*(0.0-p1.y)/(p2.y-p1.y); y=p1.y=0; p1.x=(int) x; } else if (c1 & BOTTOM) { x+=(p2.x-p1.x)*(479.0-p1.y)/(p2.y-p1.y); y=p1.y=479; p1.x=(int) x; } else if (c1 & LEFT) { y+=(p2.y-p1.y)*(0.0-p1.x)/(p2.x-p1.x); x=p1.x=0; p1.y=(int) y; } else if (c1 & RIGHT) { y+=(p2.y-p1.y)*(639.0-p1.x)/(p2.x-p1.x); x=p1.x=639; p1.y=(int) y; } c1=getcode(x,y); }/* end while */ } /* end else */ printf("original line --> (%d,%d) - (%d,%d)\n",p3.x,p3.y,p4.x,p4.y); printf("clipping line --> (%d,%d) - (%d,%d)\n",p1.x,p1.y,p2.x,p2.y); getche(); Driver = DETECT; initgraph( &Driver, &Mode, "" ); line(p3.x,p3.y,p4.x,p4.y); getche(); setcolor(6); line(p1.x,p1.y,p2.x,p2.y); getche(); closegraph(); /* Return the system to text mode */ }