這是我的算法。關鍵是我們正在減去重疊的重疊。
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
爲了確保我理解這一點,您需要重疊藍色矩形的總面積而不重複計算任何其他矩形,這些矩形也重疊在同一空間上。對? –