查找两个矩形的重叠区域(在 C# 中) [英] Finding the overlapping area of two rectangles (in C#)

查看:43
本文介绍了查找两个矩形的重叠区域(在 C# 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用来解决问题的简单代码,以防有人感兴趣(感谢 Fredrik):

Simple code I used to solve the problem in case anyone is interested (thanks to Fredrik):

    int windowOverlap(Rectangle rect1, Rectangle rect2)
    {
        if (rect1.IntersectsWith(rect2))
        {
            Rectangle overlap = Rectangle.Intersect(rect1, rect2);
            if (overlap.IsEmpty)
                return overlap.Width * overlap.Height;
        }

        return 0;
    }

原始问题:

我想知道一种快速而肮脏的方法来检查两个矩形是否重叠以及它们是否确实计算了重叠的面积.出于好奇,我对以下情况感兴趣:1) 两个矩形中的所有线都是垂直或水平的,或者 2) 任何两个矩形的一般情况,但我真正需要的唯一答案是情况 1.

I'd like to know a quick and dirty way to check if two rectangles overlap and if they do calculate the area of the overlap. For curiosities sake I'm interested in the case where 1) all the lines in both rectangles are either vertical or horizontal or 2) the general case for any two rectangles, but the only answer I really need is case 1.

我的思路是:

double areaOfOverlap( Rect A, Rect B)
{
    if ( A.Intersects(B) )
    {
        // calculate area
        // return area
    }

    return 0;
}

对于 A.Intersects() 我正在考虑使用分离轴测试,但如果矩形只有水平线和垂直线,是否有更简单(更快)的检查方法?

For A.Intersects() I was thinking of using the separating axis test, but if the rectangles have only horizontal and vertical lines is there an even simpler (faster) way to check?

如果矩形只有水平线和垂直线,那么对于计算它们相交的区域是否有一种快速的方法?

And for calculating the area where they intersect is there an quick way to do it if the rectangles only horizontal and vertical lines?

最后,这与问题无关,但我很感激有人在一本好书/网页上提出的任何建议,我可以在其中复习计算机图形学的数学.我已经离开大学一段时间了,感觉自己忘记了一切:)!其他人有这个问题吗?

Finally, this is unrelated to the question but I'd appreciate any advice someone may have on a good book / webpage where I could review the math for computer graphics. I've been out of college for a while and feel like I'm forgetting everything :)! Anyone else have that problem?

( 注意:我发现这个问题不同于 this 看起来更复杂,并没有直接回答问题.)

( NOTE: I found this question different than this which seems more complicated and doesn't directly answer the question. )

推荐答案

也许我误解了你的问题,但 Rectangle.Intersect 方法可以完成这项工作吗?它返回相交区域,然后您可以轻松计算出它的面积.

Maybe I misinterpret your question, but doesn't the Rectangle.Intersect method do the job? It returns the intersecting area, and then you can easily calculate the area of it.

这篇关于查找两个矩形的重叠区域(在 C# 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆