-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathRectangleIntersection.cs
54 lines (45 loc) · 1.4 KB
/
RectangleIntersection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
namespace Advanced.Algorithms.Geometry;
/// <summary>
/// Rectangle intersection finder.
/// </summary>
public class RectangleIntersection
{
/// <summary>
/// Returns the rectangle formed by the intersection if do intersect.
/// Otherwise default value of Rectangle struct.
/// </summary>
public static Rectangle FindIntersection(Rectangle a, Rectangle b)
{
//check for intersection
if (!DoIntersect(a, b))
//no intersection
return null;
var leftTopCorner = new Point
(
Math.Max(a.LeftTop.X, b.LeftTop.X),
Math.Min(a.LeftTop.Y, b.LeftTop.Y)
);
var rightBottomCorner = new Point
(
Math.Min(a.RightBottom.X, b.RightBottom.X),
Math.Max(a.RightBottom.Y, b.RightBottom.Y)
);
return new Rectangle
{
LeftTop = leftTopCorner,
RightBottom = rightBottomCorner
};
}
public static bool DoIntersect(Rectangle a, Rectangle b)
{
//check for intersection
if (a.LeftTop.X > b.RightBottom.X // A is right of B
|| a.RightBottom.X < b.LeftTop.X // A is left of B
|| a.RightBottom.Y > b.LeftTop.Y //A is above B
|| a.LeftTop.Y < b.RightBottom.Y) //A is below B
//no intersection
return false;
return true;
}
}