所以我有这个Panel类.这有点像一个窗口,你可以调整大小,关闭,添加按钮,滑块等.就像你们中的任何人都记得的那样,就像Morrowind中的状态屏幕一样.我想要的行为是,当一个精灵在面板边界之外时它不会被绘制,如果它部分在外部,则只绘制内部部分.所以它现在做的是首先获得一个表示面板边界的矩形,一个精灵矩形,它找到两者之间相交的矩形然后将该交集转换为精灵矩形的局部坐标并使用它对于源矩形.它的工作原理和我觉得代码一样聪明,我无法感觉到有更好的方法来做到这一点.此外,通过此设置,我无法为我的2D相机使用全局变换矩阵,"世界"中的所有内容都必须通过相机参数进行绘制.无论如何,这是我的代码:
交叉点:
public static Rectangle? Intersection(Rectangle rectangle1, Rectangle rectangle2)
{
if (rectangle1.Intersects(rectangle2))
{
if (rectangle1.Contains(rectangle2))
{
return rectangle2;
}
else if (rectangle2.Contains(rectangle1))
{
return rectangle1;
}
else
{
int x = Math.Max(rectangle1.Left, rectangle2.Left);
int y = Math.Max(rectangle1.Top, rectangle2.Top);
int height = Math.Min(rectangle1.Bottom, rectangle2.Bottom) - Math.Max(rectangle1.Top, rectangle2.Top);
int width = Math.Min(rectangle1.Right, rectangle2.Right) - Math.Max(rectangle1.Left, rectangle2.Left);
return new Rectangle(x, y, width, height);
}
}
else
{
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
并实际绘制在面板上:
public void DrawOnPanel(IDraw sprite, SpriteBatch spriteBatch)
{
Rectangle panelRectangle = new Rectangle(
(int)_position.X,
(int)_position.Y,
_width,
_height);
Rectangle drawRectangle = new Rectangle();
drawRectangle.X = (int)sprite.Position.X;
drawRectangle.Y = (int)sprite.Position.Y;
drawRectangle.Width = sprite.Width;
drawRectangle.Height = sprite.Height;
if (panelRectangle.Contains(drawRectangle))
{
sprite.Draw(
spriteBatch,
drawRectangle,
null);
}
else if (Intersection(panelRectangle, drawRectangle) == null)
{
return;
}
else if (Intersection(panelRectangle, drawRectangle).HasValue)
{
Rectangle intersection = Intersection(panelRectangle, drawRectangle).Value;
if (Intersection(panelRectangle, drawRectangle) == drawRectangle)
{
sprite.Draw(spriteBatch, intersection, intersection);
}
else
{
sprite.Draw(
spriteBatch,
intersection,
new Rectangle(
intersection.X - drawRectangle.X,
intersection.Y - drawRectangle.Y,
intersection.Width,
intersection.Height));
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我想我的问题是,有更好的方法吗?
更新:刚刚发现了ScissorRectangle属性.这似乎是一个很好的方式来做到这一点; 它需要生成一个RasterizerState对象并将其传递给接受它的spritebatch.Begin重载.看起来这可能是最好的选择.还有Viewport,我显然可以改变它.思考?:)
有多种方法可以将绘图限制在屏幕的一部分。如果该区域是矩形的(这里似乎是这种情况),您可以将视口(请参阅 GraphicsDevice)设置为面板的表面。
对于非矩形区域,您可以使用模板缓冲区或对深度缓冲区使用一些技巧。在模板缓冲区或深度缓冲区中绘制表面的形状,将渲染状态设置为仅绘制位于模板/深度缓冲区中刚刚渲染的形状中的像素,最后渲染精灵。