using System; using Microsoft.Xna.Framework; namespace MonoGame.Extended; /// /// Provides extension methods for the structure. /// public static class RectangleFExtensions { /// /// Gets the corners of the rectangle in a clockwise direction starting at the top left. /// /// The rectangle to get the corners of. /// An array of elements representing the corners of the rectangle. public static Vector2[] GetCorners(this RectangleF rectangle) { var corners = new Vector2[4]; corners[0] = new Vector2(rectangle.Left, rectangle.Top); corners[1] = new Vector2(rectangle.Right, rectangle.Top); corners[2] = new Vector2(rectangle.Right, rectangle.Bottom); corners[3] = new Vector2(rectangle.Left, rectangle.Bottom); return corners; } /// /// Converts the specified to a . /// /// The rectangle to convert. /// The converted . public static Rectangle ToRectangle(this RectangleF rectangle) { return new Rectangle((int)rectangle.X, (int)rectangle.Y, (int)rectangle.Width, (int)rectangle.Height); } /// /// Clips the specified rectangle against the specified clipping rectangle. /// /// The rectangle to clip. /// The rectangle to clip against. /// The clipped rectangle, or if the rectangles do not intersect. public static RectangleF Clip(this RectangleF rectangle, RectangleF clippingRectangle) { var clip = clippingRectangle; rectangle.X = clip.X > rectangle.X ? clip.X : rectangle.X; rectangle.Y = clip.Y > rectangle.Y ? clip.Y : rectangle.Y; rectangle.Width = rectangle.Right > clip.Right ? clip.Right - rectangle.X : rectangle.Width; rectangle.Height = rectangle.Bottom > clip.Bottom ? clip.Bottom - rectangle.Y : rectangle.Height; if (rectangle.Width <= 0 || rectangle.Height <= 0) return RectangleF.Empty; return rectangle; } /// /// Gets a rectangle that is relative to the specified source rectangle, with the specified offsets and dimensions. /// /// The source rectangle. /// The x-coordinate of the relative rectangle, relative to the source rectangle. /// The y-coordinate of the relative rectangle, relative to the source rectangle. /// The width, in pixels, of the relative rectangle. /// The height, in pixels, of the relative rectangle. /// The relative rectangle, clipped to the source rectangle. public static RectangleF GetRelativeRectangle(this RectangleF source, float x, float y, float width, float height) { float absoluteX = source.X + x; float absoluteY = source.Y + y; RectangleF relative; relative.X = MathHelper.Clamp(absoluteX, source.Left, source.Right); relative.Y = MathHelper.Clamp(absoluteY, source.Top, source.Bottom); relative.Width = Math.Max(Math.Min(absoluteX + width, source.Right) - relative.X, 0); relative.Height = Math.Max(Math.Min(absoluteY + height, source.Bottom) - relative.Y, 0); return relative; } }