diff --git a/source/MonoGame.Extended/Rectangle.Extensions.cs b/source/MonoGame.Extended/Rectangle.Extensions.cs index 7cb2becd..a6c7b4c5 100644 --- a/source/MonoGame.Extended/Rectangle.Extensions.cs +++ b/source/MonoGame.Extended/Rectangle.Extensions.cs @@ -41,16 +41,18 @@ public static class RectangleExtensions /// The clipped rectangle, or if the rectangles do not intersect. public static Rectangle Clip(this Rectangle rectangle, Rectangle 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; + int left = Math.Max(rectangle.Left, clippingRectangle.Left); + int top = Math.Max(rectangle.Top, clippingRectangle.Top); + int right = Math.Min(rectangle.Right, clippingRectangle.Right); + int bottom = Math.Min(rectangle.Bottom, clippingRectangle.Bottom); - if (rectangle.Width <= 0 || rectangle.Height <= 0) + int width = right - left; + int height = bottom - top; + + if (width <= 0 || height <= 0) return Rectangle.Empty; - return rectangle; + return new Rectangle(left, top, width, height); } /// diff --git a/tests/MonoGame.Extended.Tests/RectangleExtensionsTests.cs b/tests/MonoGame.Extended.Tests/RectangleExtensionsTests.cs new file mode 100644 index 00000000..62760a7c --- /dev/null +++ b/tests/MonoGame.Extended.Tests/RectangleExtensionsTests.cs @@ -0,0 +1,20 @@ +using Microsoft.Xna.Framework; + +namespace MonoGame.Extended.Tests +{ + public class RectangleExtensionsTests + { + [Fact] + public void Clip_ReturnsIntersectionRectangle() + { + var rect = new Rectangle(0, 0, 10, 10); + var clip1 = new Rectangle(2, 2, 5, 5); + var clip2 = new Rectangle(2, 2, 15, 15); + var clip3 = new Rectangle(-2, -2, 5, 5); + + Assert.Equal(new Rectangle(2, 2, 5, 5), rect.Clip(clip1)); + Assert.Equal(new Rectangle(2, 2, 8, 8), rect.Clip(clip2)); + Assert.Equal(new Rectangle(0, 0, 3, 3), rect.Clip(clip3)); + } + } +}