I have multiple rectangles and one special rectangle: the selection rect. I want to check for each rectangle if the rectangle contains at least one point which is inside the
Two rectangles do not overlap if one of the following conditions is true.
1) One rectangle is above top edge of other rectangle.
2) One rectangle is on left side of left edge of other rectangle.
Note that a rectangle can be represented by two coordinates, top left and bottom right. So mainly we are given following four coordinates.
l1: Top Left coordinate of first rectangle.
r1: Bottom Right coordinate of first rectangle.
l2: Top Left coordinate of second rectangle.
r2: Bottom Right coordinate of second rectangle.
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;
}
A rectangle can be defined by just one of its diagonal.
Let's say the first rectangle's diagonal is (x1, y1) to (x2, y2)
And the other rectangle's diagonal is (x3, y3) to (x4, y4)
Now, if any of these 4 conditions is true, we can conclude that the rectangles are not overlapping:
Otherwise, they overlap!
The rectangles overlap if
(x1 < x4) && (x3 < x2) && (y1 < y4) && (y3 < y2)
Sample solution on Leetcode:
https://leetcode.com/problems/rectangle-overlap/discuss/468548/Java-check-if-two-rectangles-overlap-at-any-point
Here's another simpler solution:
// 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;