这是我的算法。关键是我们正在减去重叠的重叠。
Dim baseRect As New RectangleF(10, 10, 20, 20)
Dim otherRectList As New List(Of RectangleF)
otherRectList.Add(New RectangleF(5, 5, 10, 10))
otherRectList.Add(New RectangleF(20, 20, 10, 10))
otherRectList.Add(New RectangleF(10, 5, 10, 10))
Dim overlapRectList As New List(Of RectangleF)
For Each otherRect As RectangleF In otherRectList
If RectangleF.Intersect(otherRect, baseRect) <> RectangleF.Empty Then
overlapRectList.Add(RectangleF.Intersect(otherRect, baseRect))
End If
Next
Dim totalArea As Single = 0
For Each overlapRect As RectangleF In overlapRectList
totalArea += overlapRect.Width * overlapRect.Height
Next
'Subtract out any overlaps that overlap each other
For i = 0 To overlapRectList.Count - 2
For j = i+1 To overlapRectList.Count - 1
If i <> j Then
If RectangleF.Intersect(overlapRectList(i), overlapRectList(j)) <> RectangleF.Empty Then
Dim dupeRect As RectangleF = RectangleF.Intersect(overlapRectList(i), overlapRectList(j))
totalArea -= dupeRect.Width * dupeRect.Height
End If
End If
Next
Next
我修改了代码以考虑tcarvin的注意事项。但是,我没有在方格纸上画出结果,看看它是否完全正确。我会在有更多时间后尽快查看。还请注意,我没有包含任何代码来处理少于2个交叉点的情况。
有趣的问题,花了我几分钟想出一个办法。这是功课吗? – tcarvin
这实际上是对我的工作 - 它让我陷入困境。它的主要特点是我需要识别“隐藏”的矩形,这些矩形或者完全重叠或者几乎完全重叠。现在我试图找到该区域,以便我可以识别90%覆盖(或更多)的矩形。 – lhan
为了确保我理解这一点,您需要重叠蓝色矩形的总面积而不重复计算任何其他矩形,这些矩形也重叠在同一空间上。对? –