我有多个矩形和一个特殊的选择矩形:选中矩形。我想检查每个矩形是否包含至少一个在选中矩形内的点。以下是一张图片以便清晰理解:
一个矩形可以通过其对角线来定义。
假设第一个矩形的对角线是(x1, y1)到(x2, y2)。
而另一个矩形的对角线是(x3, y3)到(x4, y4)。
现在,如果以下任何一种情况为真,则我们可以得出结论:这些矩形不重叠:
否则,它们将重叠!
如果
(x1 < x4) && (x3 < x2) && (y1 < y4) && (y3 < y2)
Leetcode上的样例解法:
https://leetcode.com/problems/rectangle-overlap/discuss/468548/Java-check-if-two-rectangles-overlap-at-any-point
这将找出矩形是否与另一个矩形重叠:
public boolean overlaps (Rectangle r) {
return x < r.x + r.width && x + width > r.x && y < r.y + r.height && y + height > r.y;
}
Rectangle.intersects
和Rectangle.contains
方法来确定它们是否相交或其中一个是否包含另一个。 // Left x
int leftX = Math.max(x1, x3);
// Right x
int rightX = Math.min(x2, x4);
// Bottom y
int botY = Math.max(y1, y3);
// TopY
int topY = Math.min(y2, y4);
if (rightX > leftX && topY > botY)
return true;
RectangularShape
,第二个是 Rectangle2D
,那么你可以简单地使用 RectangularShape.intersects
:selectionRectangle.intersects(otherRectangle)
如果以下条件之一成立,则两个矩形不会重叠。
1)一个矩形在另一个矩形的顶部边缘上方。
2)一个矩形位于另一个矩形左侧边缘的左侧。
请注意,一个矩形可以由两个坐标表示,即左上角和右下角。因此,通常我们会给出以下四个坐标。
l1:第一个矩形的左上角坐标。
r1:第一个矩形的右下角坐标。
l2:第二个矩形的左上角坐标。
r2:第二个矩形的右下角坐标。
class Point
{
int x, y;
};
// Returns true if two rectangles (l1, r1) and (l2, r2) overlap
bool doOverlap(Point l1, Point r1, Point l2, Point r2)
{
// If one rectangle is on left side of other
if (l1.x > r2.x || l2.x > r1.x)
return false;
// If one rectangle is above other
if (l1.y < r2.y || l2.y < r1.y)
return false;
return true;
}
这个类假设顺序为 left<=right
, top<=bottom
, x1<=x2
, y1<=y2
:
public class Rect
{
int left, right, bottom, top;
Rect(int left, int top, int right, int bottom)
{
this.left = left;
this.right = right;
this.top = top;
this.bottom = bottom;
}
boolean overlap(int x1, int y1, int x2, int y2)
{
// if one rectangle is to the left or right, then there can be no overlap
if(x2 < left || right < x1)
return false;
// the x values overlap, but the y values may still lie outside the rectangle
// if one rectangle is above or below, then there can be no overlap
if(y2 < top || bottom < y1)
return false;
// otherwise we must overlap !
return true;
}
}
java.awt.Rectangle
已经内置了 intersects
方法来实现这一点。
import java.awt.Rectangle;
// ...
Rectangle r1 = new Rectangle(
0 /* top left x */, 0 /* top left y */,
5 /* width */, 7 /* height */
);
Rectangle r2 = new Rectangle(4, 5, 3, 3);
System.out.println(r1.intersects(r2)); // true
Rectangle::intersects
对你可能会有帮助。 - Jeffrey