2

我很困惑为什么 XNA Rectangle 结构是这样写的。

如果我运行此代码:

var bounds = new Rectangle(0, 0, 10, 10);
        var bounds2 = new Rectangle(0, 10, 10, 10);
        var bounds3 = new Rectangle(0, 19, 10, 10);

        Debug.Print("Bounds X: {0}, Y: {1}, Top: {2} Left: {3} Bottom: {4} Right {5}", 
            bounds.X, bounds.Y, bounds.Top, bounds.Left, bounds.Bottom, bounds.Right);

        Debug.Print("Bounds2 X: {0}, Y: {1}, Top: {2} Left: {3} Bottom: {4} Right {5}",
            bounds2.X, bounds2.Y, bounds2.Top, bounds2.Left, bounds2.Bottom, bounds2.Right);

        Debug.Print("Bounds2 X: {0}, Y: {1}, Top: {2} Left: {3} Bottom: {4} Right {5}",
            bounds3.X, bounds3.Y, bounds3.Top, bounds3.Left, bounds3.Bottom, bounds3.Right);

        Debug.Print("bounds.Intersects(bounds2): {0}", bounds.Intersects(bounds2));
        Debug.Print("bounds2.Intersects(bounds3): {0}", bounds2.Intersects(bounds3));

我得到以下输出:

Bounds X: 0, Y: 0, Top: 0 Left: 0 Bottom: 10 Right 10
Bounds2 X: 0, Y: 10, Top: 10 Left: 0 Bottom: 20 Right 10
Bounds2 X: 0, Y: 19, Top: 19 Left: 0 Bottom: 29 Right 10
bounds.Intersects(bounds2): False
bounds2.Intersects(bounds3): True

这表明 Intersects 方法可以正常工作,因为bounds不重叠bounds2bounds2确实重叠bounds3了一行像素。

然而,对我来说,Bottom和的输出Right似乎很奇怪。它们都报告的值比我认为应该的值大 1 像素,我总是被它抓住,造成挫败感。

例如,我可能会使用矩形来为矩形精灵创建一个边界框。为方便起见,我喜欢使用Width、和值Height,但和值并没有给我纹理像素的底行和右列,它们给了我正好在底部下方的行和列到纹理的右侧。RightBottomRightBottom

它有这样的工作原理吗?您是否在 XNA 中使用 Rectangle 作为边界框,如果是,您是否注意到相同的行为,或者您能否提供任何建议来改进我的方法?

谢谢

4

2 回答 2

5

I don't really see your problem. If a rectangle starts at Left = 1 and has a Width of 3, then it reaches from pixels 1 to 4:

Rectangle

In the above picture I chose the pixel's center as its position. If we say, the pixel's location is its top left corner, then the figure looks as follows:

Rectangle

Then the rectangle reaches from the top left corner of pixel 1 to the top left corner of pixel 4. What might confuse you is that the top left corner of pixel 4 is the top right corner of pixel 3. But that's all up to your interpretation of the rectangle. If you keep interpretation consistent, then it all makes sense.

于 2013-06-21T07:49:19.613 回答
3

Windows APIRect结构也是如此,至少可以追溯到 Windows 3.x。

原因是它简化了一些计算。

这是 2004 年关于它的博客条目:http: //blogs.msdn.com/b/oldnewthing/archive/2004/02/18/75652.aspx

请注意,出于类似的原因,GDI 线图(可能还有 XNA 线图)也使用专有端点。

于 2013-06-21T07:48:20.753 回答