Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Or just use/copy the code already in the Java method</p> <pre><code>java.awt.geom.Rectangle2D.intersectsLine(double x1, double y1, double x2, double y2) </code></pre> <p>Here is the method after being converted to static for convenience:</p> <pre><code>/** * Code copied from {@link java.awt.geom.Rectangle2D#intersectsLine(double, double, double, double)} */ public class RectangleLineIntersectTest { private static final int OUT_LEFT = 1; private static final int OUT_TOP = 2; private static final int OUT_RIGHT = 4; private static final int OUT_BOTTOM = 8; private static int outcode(double pX, double pY, double rectX, double rectY, double rectWidth, double rectHeight) { int out = 0; if (rectWidth &lt;= 0) { out |= OUT_LEFT | OUT_RIGHT; } else if (pX &lt; rectX) { out |= OUT_LEFT; } else if (pX &gt; rectX + rectWidth) { out |= OUT_RIGHT; } if (rectHeight &lt;= 0) { out |= OUT_TOP | OUT_BOTTOM; } else if (pY &lt; rectY) { out |= OUT_TOP; } else if (pY &gt; rectY + rectHeight) { out |= OUT_BOTTOM; } return out; } public static boolean intersectsLine(double lineX1, double lineY1, double lineX2, double lineY2, double rectX, double rectY, double rectWidth, double rectHeight) { int out1, out2; if ((out2 = outcode(lineX2, lineY2, rectX, rectY, rectWidth, rectHeight)) == 0) { return true; } while ((out1 = outcode(lineX1, lineY1, rectX, rectY, rectWidth, rectHeight)) != 0) { if ((out1 &amp; out2) != 0) { return false; } if ((out1 &amp; (OUT_LEFT | OUT_RIGHT)) != 0) { double x = rectX; if ((out1 &amp; OUT_RIGHT) != 0) { x += rectWidth; } lineY1 = lineY1 + (x - lineX1) * (lineY2 - lineY1) / (lineX2 - lineX1); lineX1 = x; } else { double y = rectY; if ((out1 &amp; OUT_BOTTOM) != 0) { y += rectHeight; } lineX1 = lineX1 + (y - lineY1) * (lineX2 - lineX1) / (lineY2 - lineY1); lineY1 = y; } } return true; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload