Advertisement
fosterboy123

AABB

Aug 9th, 2012
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.48 KB | None | 0 0
  1. /// <summary>
  2. /// Calculates an axis aligned rectangle which fully contains an arbitrarily
  3. /// transformed axis aligned rectangle.
  4. /// </summary>
  5. /// <param name="rectangle">Original bounding rectangle.</param>
  6. /// <param name="transform">World transform of the rectangle.</param>
  7. /// <returns>A new rectangle which contains the trasnformed rectangle.</returns>
  8. public static Rectangle CalculateBoundingRectangle(Rectangle rectangle, Matrix transform)
  9. {
  10.     // Get all four corners in local space
  11.     Vector2 leftTop = new Vector2(rectangle.Left, rectangle.Top);
  12.     Vector2 rightTop = new Vector2(rectangle.Right, rectangle.Top);
  13.     Vector2 leftBottom = new Vector2(rectangle.Left, rectangle.Bottom);
  14.     Vector2 rightBottom = new Vector2(rectangle.Right, rectangle.Bottom);
  15.  
  16.     // Transform all four corners into work space
  17.     Vector2.Transform(ref leftTop, ref transform, out leftTop);
  18.     Vector2.Transform(ref rightTop, ref transform, out rightTop);
  19.     Vector2.Transform(ref leftBottom, ref transform, out leftBottom);
  20.     Vector2.Transform(ref rightBottom, ref transform, out rightBottom);
  21.  
  22.     // Find the minimum and maximum extents of the rectangle in world space
  23.     Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop),
  24.                               Vector2.Min(leftBottom, rightBottom));
  25.     Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop),
  26.                               Vector2.Max(leftBottom, rightBottom));
  27.  
  28.     // Return as a rectangle
  29.     return new Rectangle((int)min.X, (int)min.Y,
  30.                          (int)(max.X - min.X), (int)(max.Y - min.Y));
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement