Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

math - Java check if two rectangles overlap at any point

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...