二分法快速判断点是不是在凸多边形内
2018-08-23 本文已影响0人
梁间
public func isInside(point:CGPoint, con:[CGPoint]) -> Bool{
if con.count < 3 {
return false
}
if multiply(sp: point, ep: con[1], op: con[0]) < 0{
return false
}
if multiply(sp: point, ep: con[con.count-1], op: con[0]) < 0{
return false
}
var i = 2
var j = con.count - 1
var line = -1
while i <= j {
let mid = (i+j)>>1
if multiply(sp: point, ep: con[mid], op: con[0]) > 0{
line = mid
j = mid - 1
}else{
i = mid + 1
}
}
return multiply(sp: point, ep: con[line], op: con[line-1]) < 0
}
/*
r=multiply(sp,ep,op),得到(sp-op)和(ep-op)的叉积
r>0:ep在矢量opsp的逆时针方向;
r=0:opspep三点共线;
r<0:ep在矢量opsp的顺时针方向
*/
public func multiply(sp:CGPoint,ep:CGPoint,op:CGPoint) -> CGFloat{
return (sp.x - op.x)*(ep.y - op.y) - (ep.x - op.x)*(sp.y - op.y)
}