The source code for Rectangle2D.intersectLine()
[anchor link not working] might be helpful:
public boolean intersectsLine(double x1, double y1, double x2, double y2) {
int out1, out2;
if ((out2 = outcode(x2, y2)) == 0) {
return true;
}
while ((out1 = outcode(x1, y1)) != 0) {
if ((out1 & out2) != 0) {
return false;
}
if ((out1 & (OUT_LEFT | OUT_RIGHT)) != 0) {
double x = getX();
if ((out1 & OUT_RIGHT) != 0) {
x += getWidth();
}
y1 = y1 + (x - x1) * (y2 - y1) / (x2 - x1);
x1 = x;
} else {
double y = getY();
if ((out1 & OUT_BOTTOM) != 0) {
y += getHeight();
}
x1 = x1 + (y - y1) * (x2 - x1) / (y2 - y1);
y1 = y;
}
}
return true;
}
where outcode()
is defined as:
public int outcode(double x, double y) {
int out = 0;
if (this.width <= 0) {
out |= OUT_LEFT | OUT_RIGHT;
} else if (x < this.x) {
out |= OUT_LEFT;
} else if (x > this.x + this.width) {
out |= OUT_RIGHT;
}
if (this.height <= 0) {
out |= OUT_TOP | OUT_BOTTOM;
} else if (y < this.y) {
out |= OUT_TOP;
} else if (y > this.y + this.height) {
out |= OUT_BOTTOM;
}
return out;
}
(from OpenJDK)
It shouldn't be extremely difficult to change this to clip instead of returning true or false.