Click on any two points in the outer box to draw lines. You should find you can
only see that part of the lines that is inside the black box, i.e. the lines get
cut off at the black box.
Credits: This is an applet adaptation of a program by Pete
Williams. I have been inspired by the elegance, beauty and simplicity of many of
his programs, and can only hope that with practice my own programs become as
parsimonious.
Code:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
class Point
{
double x,y;
Point(double thisx, double thisy)
{
x=thisx;
y=thisy;
}
}
public class lineClipper extends Applet
{
final int xMax = 500,yMax = 400;
private int firstX, firstY,lastX,lastY,points = 0;
static double xLeft=100.0, xRight=400.0,yBottom=100.0, yTop=300.0;
//dimensions of rectangle to clip against
Point P0,P1;
public void init()
{
resize( xMax, yMax );
this.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent evt)
{
if(points == 0) { firstX=evt.getX(); firstY=evt.getY(); points++;}
else if (points == 1)
{lastX=evt.getX(); lastY=evt.getY(); points = 0;
P0 = new Point((double)firstX,(double)firstY);
P1 = new Point((double)lastX,(double)lastY);
paint(getGraphics());}
}});
show();
}
public void paint(Graphics g)
{
g.drawRect((int)xLeft,(int)yBottom, (int)(xRight-xLeft), (int)(yTop-yBottom));
if(CohenSutherland2DClipper(P0,P1))
g.drawLine((int)P0.x,(int)P0.y, (int)P1.x,(int)P1.y);
}
private static int outCodes(Point P)
{
int Code = 0;
if(P.y > yTop) Code += 1; /* code for above */
else if(P.y < yBottom) Code += 2; /* code for below */
if(P.x > xRight) Code += 4; /* code for right */
else if(P.x < xLeft) Code += 8; /* code for left */
return Code;
}
private static boolean rejectCheck(int outCode1, int outCode2)
{
if ((outCode1 & outCode2) != 0 ) return true;
return(false);
}
private static boolean acceptCheck(int outCode1, int outCode2)
{
if ( (outCode1 == 0) && (outCode2 == 0) ) return(true);
return(false);
}
static boolean CohenSutherland2DClipper(Point P0,Point P1)
{
int outCode0,outCode1;
while(true)
{
outCode0 = outCodes(P0);
outCode1 = outCodes(P1);
if( rejectCheck(outCode0,outCode1) ) return(false);
if( acceptCheck(outCode0,outCode1) ) return(true);
if(outCode0 == 0)
{
double tempCoord; int tempCode;
tempCoord = P0.x; P0.x= P1.x; P1.x = tempCoord;
tempCoord = P0.y; P0.y= P1.y; P1.y = tempCoord;
tempCode = outCode0; outCode0 = outCode1; outCode1 = tempCode;
}
if( (outCode0 & 1) != 0 )
{
P0.x += (P1.x - P0.x)*(yTop - P0.y)/(P1.y - P0.y);
P0.y = yTop;
}
else
if( (outCode0 & 2) != 0 )
{
P0.x += (P1.x - P0.x)*(yBottom - P0.y)/(P1.y - P0.y);
P0.y = yBottom;
}
else
if( (outCode0 & 4) != 0 )
{
P0.y += (P1.y - P0.y)*(xRight - P0.x)/(P1.x - P0.x);
P0.x = xRight;
}
else
if( (outCode0 & 8) != 0 )
{
P0.y += (P1.y - P0.y)*(xLeft - P0.x)/(P1.x - P0.x);
P0.x = xLeft;
}
}
}
}