Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two areas are in contact [duplicate]

Tags:

Possible Duplicate:
Finding the overlapping area of two rectangles (in C#)

I have two areas identified by top left and bottom right corners (fig.1).

In c#, how can I test if they are in contact (fig.2)?

enter image description here

like image 927
A.Baudouin Avatar asked Feb 02 '13 14:02

A.Baudouin


People also ask

How can I find duplicate contacts?

On your Android phone or tablet, open the Contacts app . At the top right, select the Google Account that has the duplicate contacts you want to merge. At the bottom, tap Fix & manage Merge & fix. Tap Merge duplicates.

Why do I have so many duplicate contacts on my iPhone?

Duplicate contacts on your iPhone can occur as the result of using iCloud, or due to an issue with your address book or email client on your computer. When using your iPhone for both your business and personal purposes, you may create duplicate contacts by syncing with more than one service.


2 Answers

Let's say you have two Rectangles which are r1 and r2, you can check whether they intersects with each other by this:

if(r1.IntersectsWith(r2))
{
    // Intersect
}

If you need the exact area which they intersects with each other, you can do this:

Rectangle intersectArea = Rectangle.Intersect(r1, r2);

You can check the documentation: Rectangle.IntersectsWith, Rectangle.Intersect


Additional important note:

I've just checked that if the two rectangles just touch each other on an edge, Rectangle.Intersect returns a rectangle with one dimension is zero , however Rectangle.IntersectsWith will return false. So you need to note that.

For example, Rectangle.Intersect on {X=0,Y=0,Width=10,Height=10} and {X=10,Y=0,Width=10,Height=10} will return {X=10,Y=0,Width=0,Height=10}.

If you hope to get true also if they just touch each other, change the condition to:

if(Rectangle.Intersect(r1, r2) != Rectangle.Empty)
{
    // Intersect or contact (just touch each other)
}
like image 66
Alvin Wong Avatar answered Oct 20 '22 09:10

Alvin Wong


If you don't want to depend on System.Drawing:

Let's note:

  • X1, Y1, X2, Y2 : the coordinates of the points of the first rectangle (with X1 < X2 and Y1 < Y2)
  • X1', Y1', X2', Y2' : the coordinates of the points of the second rectangle (with X1' < X2' and Y1' < Y2')

There is intersection if and only if:

(X2' >= X1 && X1' <= X2) && (Y2' >= Y1 && Y1' <= Y2)
like image 37
Cédric Bignon Avatar answered Oct 20 '22 09:10

Cédric Bignon