Check if two areas are in contact

A.Baudouin picture A.Baudouin · Feb 2, 2013 · Viewed 20k times · Source

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

Answer

Alvin Wong picture Alvin Wong · Feb 2, 2013

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)
}