我在这里重新使用了sijipie的代码:https://www.mrexcel.com/forum/excel-questions/713005-does-point-fall-within-polygon-visual-basic-applications-function.html
我需要做的是确定一条线是否在多边形内。
不可否认,这有点懒,因为我没有测试线与每一边的交点,因为我迭代线的中点并测试它们作为内点。
我想知道是否有更快的方法来做到这一点。
以下VBA代码:
Function PolyLineIntersect(lXY As Range, polyXY As Range) As Boolean
Dim i As Integer, j As Integer, a As Integer, polySides As Integer
Dim Result As Boolean
Dim x As Double, y As Double
Dim aXY As Variant
Dim mXY(1 To 5, 1 To 2) As Integer
Dim tXY(1 To 5) As Boolean
x = lXY.Cells.value2(1, 1)
y = lXY.Cells.value2(1, 2)
xb = lXY.Cells.value2(1, 3)
yb = lXY.Cells.value2(1, 4)
mXY(1, 1) = x
mXY(1, 2) = y
mXY(2, 1) = xb
mXY(2, 2) = yb
mXY(3, 1) = (xb + x) / 2
mXY(3, 2) = (yb + y) / 2
mXY(4, 1) = (xb + mx1) / 2
mXY(4, 2) = (yb + my1) / 2
mXY(5, 1) = (xb + mx1) / 2
mXY(5, 2) = (yb + my1) / 2
Result = False
aXY = polyXY.Value
polySides = polyXY.Rows.Count
j = polySides - 1
For a = 1 To 5
x = mXY(a, 1)
y = mXY(a, 2)
For i = 1 To polySides
If (((aXY(i, 2) < y And aXY(j, 2) >= y) _
Or (aXY(j, 2) < y And aXY(i, 2) >= y)) _
And (aXY(i, 1) <= x Or aXY(j, 1) <= x)) Then
Result = Result Xor (aXY(i, 1) + (y - aXY(i, 2)) / (aXY(j, 2) - aXY(i, 2)) * (aXY(j, 1) - aXY(i, 1)) < x)
End If
j = i
Next i
Next a
PolyLineIntersect = Result
End Function
答案 0 :(得分:0)
使用cross product检查所有多边形顶点是否位于相对于给定线的同一半平面(左侧或右侧)中。如果是,则线不与多边形相交。
Side = Sign(CrossProduct(L2-L1, P[i] - L1))
where L1, L2 are points defining the line, P[i] is i-th polygon vertex
算法在线性时间O(N)中工作,其中N是多边形顶点计数。请注意,对于凸多边形,可以使用二分搜索在O(logN)时间推导出结果。