Swift:有没有简单的方法来绘制形状并检测它们是否相交?

有没有一种简单的方法来在Swift中绘制形状(最好使用Sprite-Kit),然后检测它们是否在相交处? 像这里是一个相交的形状:

在这里输入图像说明

如果这包括一系列线段,则可以使Martin R的答案适应UIBezierPath相交,以不仅检测交叉点,而且还识别交叉点的位置:

func intersectionBetweenSegments(p0: CGPoint, _ p1: CGPoint, _ p2: CGPoint, _ p3: CGPoint) -> CGPoint? { var denominator = (p3.y - p2.y) * (p1.x - p0.x) - (p3.x - p2.x) * (p1.y - p0.y) var ua = (p3.x - p2.x) * (p0.y - p2.y) - (p3.y - p2.y) * (p0.x - p2.x) var ub = (p1.x - p0.x) * (p0.y - p2.y) - (p1.y - p0.y) * (p0.x - p2.x) if (denominator < 0) { ua = -ua; ub = -ub; denominator = -denominator } if ua >= 0.0 && ua <= denominator && ub >= 0.0 && ub <= denominator && denominator != 0 { return CGPoint(x: p0.x + ua / denominator * (p1.x - p0.x), y: p0.y + ua / denominator * (p1.y - p0.y)) } return nil } 

因此,如果你有一个CGPoint值的数组,并且你想识别所有的交叉点,你可以这样做:

 let n = points!.count - 1 for i in 1 ..< n { for j in 0 ..< i-1 { if let intersection = intersectionBetweenSegments(points![i], points![i+1], points![j], points![j+1]) { // do whatever you want with `intersection` } } } 

例如,您可以在分段相交的屏幕上添加一个点:

贝塞尔曲线交点

但是,如果曲线由三次贝塞尔曲线组成,则更为复杂。 但是,您可能会考虑检查两个三次Bézier曲线是否相交 。

Interesting Posts