Line Clipping: To Write The C Programs For Implementation of Line Clipping
Line Clipping: To Write The C Programs For Implementation of Line Clipping
LINE CLIPPING
Aim:
To write the C programs for implementation of line clipping.
Procedure:
Step 1: Declare the necessary variables and using the initgraph() to initialize the driver.
Step 2: Generate the region code
LEFT:
x = xwmin
y = y+m(x-x1) here m = (y-y1)/(x-x1)
RIGHT:
x = xwmax;
y = y+m(x-x1); here m = (y-y1)/(x-x1)
ABOVE:
y=ywmin;
x=x1+(y-y1)/m; here m = (y-y1)/(x-x1)
BELOW:
y=ywmin;
x=x1+(y-y1)/m; here m = (y-y1)/(x-x1)
Step 7: Repeat the Step 6 until the point is completely inside or outside. Finally clipped line will
be displayed.
Program:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm,xwmin=100,xwmax=400,ywmin=100,ywmax=400,x1,x,y,y1,x2,y2;
float m1,m2,m=0.0;6
int above=0x8;
int below=0x4;
int right=0x2;
int left=0x1;
int p1,p2;
clrscr();
initgraph(&gd,&gm,"f:\\tc\\bgi.");
printf("Enter the values for line:");
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
outtextxy(95,90,"(100,100)");
outtextxy(405,405,"(400,400)");
outtextxy(150,50,"Before Clip");
rectangle(xwmin,ywmin,xwmax,ywmax);
line(x1,y1,x2,y2);
getch();
cleardevice();
while(5)
{
p1=0x0;
p2=0x0;
m1=y2-y1;
m2=x2-x1;
if(m2!=0)
m=m1/m2;
if(x1<xwmin)
p1|=left;
if(x1>xwmax)
p1|=right;
if(y1<ywmin)
p1|=above;
if(y1>ywmax)
p1|=below;
if(x2<xwmin)
p2|=left;
if(x2>xwmax)
p2|=right;
if(y2<ywmin)
p2|=above;
if(y2>ywmax)
p2|=below;
if((p1|p2)==0)
{
outtextxy(150,50,"After Clip");
rectangle(xwmin,ywmin,xwmax,ywmax);
line(x1,y1,x2,y2);
getch();
break;
}
else if((p1&p2)!=0)
{
outtextxy(150,50,"After Clip");
rectangle(xwmin,ywmin,xwmax,ywmax);
getch();
break;
}
else
{
//printf("partially outside");
if(p1!=0)
{
//printf("starting point");
if((p1&left)!=0)
{
x=xwmin;
y=y1+m*(x-x1);
x1=x;
y1=y;
}
if((p1&right)!=0)
{
x=xwmax;
y=y1+m*(x-x1);
x1=x;
y1=y;
}
if((p1&above)!=0)
{
y=ywmin;
if(m!=0)
{
x=x1+(y-y1)/m;
}
else
{
x=x1;
}
x1=x;
y1=y;
}
if((p1&below)!=0)
{
y=ywmax;
if(m!=0)
{
x=x1+(y-y1)/m;
}
else
{
x=x1;
}
x1=x;
y1=y;
}
}
else
{
//printf("endpoint");
if((p2&left)!=0)
{
x=xwmin;
y=y2+m*(x-x2);
x2=x;
y2=y;
}
if((p2&right)!=0)
{
x=xwmax;
y=y2+m*(x-x2);
x2=x;
y2=y;
}
if((p2&above)!=0)
{
y=ywmin;
if(m!=0)
{
x=x2+(y-y2)/m;
}
else
{
x=x2;
}
x2=x;
y2=y;
}
if((p2&below)!=0)
{y=ywmax;
if(m!=0)
{
x=x2+(y-y2)/m;
}
else
{
x=x2;
}
x2=x;
y2=y;
}
}}}
getch();
}
Output:
Enter the value for line: 75 75 450 450