Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java check if two rectangles overlap at any point

Tags:

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 selection rectangle. Here is an image for clarity:

Selection example

like image 566
user2190492 Avatar asked Apr 25 '14 20:04

user2190492


People also ask

Do you check if two rectangles overlap with each other?

Problem Statement Its top and bottom edges are perpendicular to the X-axis, while its left and right edges are perpendicular to the Y-axis. If the area of their intersection is positive, two rectangles overlap. Two rectangles that touch at the corners or edges do not overlap.

How do you compare two rectangles?

Explanation: For two rectangles to be similar, their sides have to be proportional (form equal ratios). The ratio of the two longer sides should equal the ratio of the two shorter sides.


2 Answers

Background:

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)

Sample

Proceeding:

Now, if any of these 4 conditions is true, we can conclude that the rectangles are not overlapping:

  1. x3 > x2 (OR)
  2. y3 > y2 (OR)
  3. x1 > x4 (OR)
  4. y1 > y4


Otherwise, they overlap!

enter image description here

Alternatively:

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

like image 89
ThePatelGuy Avatar answered Sep 21 '22 09:09

ThePatelGuy


This will find if the rectangle is overlapping another rectangle:

public boolean overlaps (Rectangle r) {     return x < r.x + r.width && x + width > r.x && y < r.y + r.height && y + height > r.y; } 
like image 37
CodeCamper Avatar answered Sep 20 '22 09:09

CodeCamper