Lets say I have an XNA Rectangle with
X = 0, Y = 0, Width = 25, Height = 25.
What I want is a method to clamp another rectangle inside, so that the smaller rectangle never ‘leaves’ the bounds of the larger one.
For example, if I make a new Rectangle with:
X = 23, Y = 20, Width = 10, Height = 10,
I want the method to return a Rectangle with:
X = 23, Y = 20, Width = 2, Height = 5.
Also, if I make a new Rectangle with:
X = -8, Y = 8, Width = 10, = 10,
I want the method to return a Rectangle with:
X = 0, Y = 8, Width = 2, Height = 10.
In the meanwhile I got the clamping to work. Still, its a bulk of ugly code, so the new question is, how can I simplify this?
if (SelectionRectangle.X < 0)
{
SelectionRectangle.Width = SelectionRectangle.Width + SelectionRectangle.X;
SelectionRectangle.X = 0;
}
if (SelectionRectangle.X + SelectionRectangle.Width > tileset.Width)
{
if (SelectionRectangle.X > tileset.Width)
{
SelectionRectangle.X = tileset.Width;
SelectionRectangle.Width = 0;
}
else
{
SelectionRectangle.Width = tileset.Width - SelectionRectangle.X;
}
}
if (SelectionRectangle.Y < 0)
{
SelectionRectangle.Height = SelectionRectangle.Height + SelectionRectangle.Y;
SelectionRectangle.Y = 0;
}
if (SelectionRectangle.Y + SelectionRectangle.Height > tileset.Height)
{
if (SelectionRectangle.Y > tileset.Height)
{
SelectionRectangle.Y = tileset.Height;
SelectionRectangle.Height = 0;
}
else
{
SelectionRectangle.Height = tileset.Height - SelectionRectangle.Y;
}
}
Isn’t this just
Rectangle.Intersect?If the smaller rectangle is entirely within the larger rectangle, then the intersection will be the same as the smaller rectangle. If the smaller rectangle extends outside of the larger rectangle, that portion will not be returned.