从贝塞尔路径计算点

Compute points from Bezier Path

假设我有一条随机贝塞尔曲线路径,如下所示:

let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 3, y: 0.84))
bezierPath.addCurve(to: CGPoint(x: 11, y: 8.84), controlPoint1: CGPoint(x: 3, y: 1.84), controlPoint2: CGPoint(x: 9, y: 4.59))
// [...]
bezierPath.addCurve(to: CGPoint(x: 3, y: 0.84), controlPoint1: CGPoint(x: 7, y: 4.84), controlPoint2: CGPoint(x: 3, y: -0.16))
bezierPath.close()

我想创建一个函数来计算给定百分比的 CGPoint,其中 0% 是 bezierPath 的第一个点,100% 是最后一个点:

extension UIBezierPath {
    func getPointFor(percentage: Float) -> CGPoint {
        //Computation logic
        return result
    }
}

我找到了这个 post 但解决方案不允许我获得所有点(例如,位置在路径的 15.5%)。

有办法吗?

我找到了 objective-c 中写的解决方案。你可以找到源代码here.

我设法通过 bridging header :

来使用它
#ifndef bridging_header_h
#define bridging_header_h

#import "UIBezierPath+Length.h"

#endif /* bridge_header_h */

您可以像这样使用这两个函数:

print("length=\(bezierPath.length())")
for i in 0...100 {
    let percent:CGFloat = CGFloat(i) / 100.0
    print("point at [\(percent)]=\(bezierPath.point(atPercentOfLength: percent))")
}

输出:

length=143.316117804497
point at [0.0]=(3.0, 0.839999973773956)
point at [0.01]=(3.26246070861816, 1.29733419418335)
point at [0.02]=(3.97137236595154, 1.91627132892609)
point at [0.03]=(5.00902938842773, 2.69386911392212)
[...]
point at [0.99]=(3.27210903167725, 0.765813827514648)
point at [1.0]=(3.0, 0.839999973773956)