public bool DoRectanglesIntersect(Rectange r1, Rectange r2) { var condition1 = r2.Left > r1.Right; //R1 is totally left of R2 var condition2 = r2.Right < r1.Left; //R1 is totall right of R2 var condition3 = r2.Top < r1.Bottom; //R1 is on top of R2 var condition4 = r2.Bottom > r1.Top; //R1 is on the bottom of R2 return(!(condition1 || condition2 || condition3 || condition4)); }
//more than 2 rectanges, rectanges can be rotated at an angle public Rectange IntersectionOfRectangle(Rectange r1, Rectange r2) { if (r1 == null) { return(r2); } if (r2 == null) { return(r1); } return(new Rectange() { Top = Math.Max(r1.Top, r2.Top), Bottom = Math.Min(r1.Bottom, r2.Bottom), Left = Math.Max(r1.Left, r2.Left), Right = Math.Min(r1.Right, r2.Right) }); }