Code Snippets #3 – Rectangle Intersects

Published 2/18/2013 by createdbyx in Code Snippets | Example | News | Programming
Tags: ,
```        /// <summary>
/// Determines if this rectangle intersects with rect.
/// </summary>
/// <param name="rect">
/// The rectangle to test.
/// </param>
/// <returns>
/// This method returns true if there is any intersection, otherwise false.
/// </returns>
public bool Intersects(RectangleF rect)
{
return !((this.X > rect.Right) || (this.Right < rect.Left) || (this.Y > rect.Bottom) || (this.Bottom < rect.Top));
}

/// <summary>
/// Replaces this RectangleF with the intersection of itself and the specified RectangleF.
/// </summary>
/// <param name="rect">
/// The RectangleF with which to intersect.
/// </param>
public void Intersect(RectangleF rect)
{
this.X = Math.Max(this.Left, rect.Left);
this.Y = Math.Max(this.Top, rect.Top);
this.Width = Math.Min(this.Right, rect.Right) - this.X;
this.Height = Math.Min(this.Bottom, rect.Bottom) - this.Y;
}

/// <summary>
/// Returns a third RectangleF structure that represents the intersection of two other RectangleF structures.
/// If there is no intersection, an empty RectangleF is returned.
/// </summary>
/// <param name="a">
/// A rectangle to intersect.
/// </param>
/// <param name="b">
/// B rectangle to intersect.
/// </param>
/// <returns>
/// A RectangleF that represents the intersection of a and b.
/// </returns>
public static RectangleF Intersect(RectangleF a, RectangleF b)
{
float x = Math.Max((sbyte)a.X, (sbyte)b.X);
float num2 = Math.Min(a.X + a.Width, b.X + b.Width);
float y = Math.Max((sbyte)a.Y, (sbyte)b.Y);
float num4 = Math.Min(a.Y + a.Height, b.Y + b.Height);
if ((num2 >= x) && (num4 >= y))
{
return new RectangleF(x, y, num2 - x, num4 - y);
}

return Empty;
}```

• Comment
• Preview

Created by: X

Just another personal website in this crazy online world

 Dean Lunz (aka Created by: X) Computer programming nerd, and tech geek. About Me -- Resume