来自Bezier Path的计算点

时间:2016-11-07 17:47:23

标签: swift uibezierpath bezier

假设我有一条随机bezier路径,如下所示:

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%是第一个点,100%是bezierPath的最后一个点:

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

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

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:1)

我找到了一个用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)