简体   繁体   English

计算两个矩形之间的相交面积

[英]Calculating area of intersection between two rectangles

//C# Console Application Home assignment

I have 8 coordinates like this: 我有8个这样的坐标:

(x1, y1) (x2, y2) ... (x8, y8) //The first 4 coordinates are for 1st rectangle //The rest for 2nd rectangle (x1,y1)(x2,y2)...(x8,y8)//前四个坐标用于第一个矩形//其余的用于第二个矩形

I store the values like this: 我存储这样的值:

int[,] array2D = new int[8,2];
array2d[0,0] = x1;
array2d[0,1] = y1;
array2d[1,0] = x2;
array2d[1,1] = y2;
//...
array[7,0] = x8;
array[7,1] = y8;

I want to calculate area of intersection between those coordinates. 我想计算这些坐标之间的相交面积。

I already have this code to check when the rectangles aren't overlapping (it works): 我已经有了以下代码来检查矩形何时不重叠(它可以工作):

if (!(array2D[2, 1] <= array2D[4, 1] && array2D[0, 1] >= array2D[6, 1]
                && array2D[2, 0] >= array2D[4, 0] && array2D[0, 0] <= array2D[6, 0]))
            {
//not overlapping
}
{
//overlapping
}

I need help with algorithm to get the area of intersection. 我需要算法帮助来获取相交区域。

NOTE: Coordinates can have negative values. 注意:坐标可以具有负值。

I would use the Rectangle.Intersect method from System.Drawing . 我将使用System.Drawing Rectangle.Intersect方法 There's no point in reinventing the wheel... ;-) 重新发明轮子没有意义... ;-)

Returns a third Rectangle structure that represents the intersection of two other Rectangle structures. 返回表示其他两个Rectangle结构的交集的第三个Rectangle结构。 If there is no intersection, an empty Rectangle is returned. 如果没有交集,则返回一个空的Rectangle。

The simplest solution is to first note that intersection of rectangles (or indeed anything) is commutative. 最简单的解决方案是首先注意矩形(或其他任何东西)的交集是可交换的。 That is, if I want to intersect A, B and C, I can intersect A and B and then intersect that with C OR intersect B and C and then intersect the result with A. 也就是说,如果我要与A,B和C相交,我可以与A和B相交,然后与C相交, 或者与B和C相交,然后与A相交。

Therefore, store a rectangle and intersect it with successive rectangles. 因此,存储一个矩形并将其与连续的矩形相交。 So you start with the first rectangle, intersect that with the second. 因此,您从第一个矩形开始,与第二个矩形相交。 Then you intersect the result with the third and so on. 然后将结果与第三个相交,依此类推。

This will give you the intersection rectangle, so you can simply compute the area. 这将为您提供相交矩形,因此您可以简单地计算面积。

Update 更新

Your problem seems to mainly be your format for your rectangles. 您的问题似乎主要是矩形的格式。 Namely, the 4 vertices defining the rectangle. 即,定义矩形的4个顶点。 This can easily be turned in to an X/Y for the top left and a width and height by taking the top left to be your first vertex (obviously), the width and height are the difference between this vertex and the bottom right 通过将左上角作为您的第一个顶点(很明显),可以轻松地将其转换为左上角的X / Y和宽度和高度,宽度和高度是该顶点与右下角之间的差

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM