mirror of
https://github.com/AlexMacocian/MonoGame.Extended.git
synced 2026-07-15 15:09:29 +00:00
fixed broken Rectangle.Clip() extensions method (#998)
(rectangle.Right depends on rectangle.X, which has been changed before; unit test will fail with old implementation)
This commit is contained in:
@@ -41,16 +41,18 @@ public static class RectangleExtensions
|
||||
/// <returns>The clipped rectangle, or <see cref="Rectangle.Empty"/> if the rectangles do not intersect.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user