18

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

Community
  • 1
  • 1
A.Baudouin
  • 2,407
  • 2
  • 22
  • 26
  • 2
    http://stackoverflow.com/questions/1551243/finding-the-overlapping-area-of-two-rectangles-in-c?rq=1 – Nemanja Boric Feb 02 '13 at 14:18
  • 1
    @Burgos [`Rectangle.IntersectsWith`](http://msdn.microsoft.com/en-us/library/system.drawing.rectangle.intersectswith.aspx) is actually more specific to the problem. I would say not *exactly* a duplicate. – Alvin Wong Feb 02 '13 at 14:21

2 Answers2

32

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)
}
Alvin Wong
  • 11,512
  • 5
  • 44
  • 73
15

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)
Cédric Bignon
  • 11,982
  • 3
  • 35
  • 50