在单个 CAShapeLayer 中动画多个 UIBezier 路径

Animating multiple UIBezier paths in a single CAShapeLayer

我想在屏幕上绘制多个字母的动画。我的数据在一个数组中。该数组包含线对象,这些线对象具有动画的开始和结束时间,以及构成线的点。我目前的代码如下:

private func animateSentData(data: WhiteboardData) {
        // I currently only draw a single letter
        let path: UIBezierPath = UIBezierPath()
        if let line = data.lines.first {
            for (n, point) in line.pts.enumerated() {
                let translation: (CGFloat, CGFloat) = (point.x / data.w, point.y / data.h)
                if n == 0 {
                    path.move(to: CGPoint(x: view.frame.width * translation.0, y: view.frame.height * translation.1))
                } else {
                    path.addLine(to: CGPoint(x: view.frame.width * translation.0, y: view.frame.height * translation.1))
                }
            }
        }
        let shapelayer: CAShapeLayer = CAShapeLayer()
        shapelayer.path = path.cgPath
        shapelayer.strokeColor = UIColor.black.cgColor
        shapelayer.fillColor = UIColor.clear.cgColor
        shapelayer.lineCap = kCALineCapRound
        shapelayer.lineWidth = brushWidth

        shapelayer.frame = view.bounds
        view.layer.addSublayer(shapelayer)
        let animation: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
        animation.fromValue = 0
        animation.duration = 3.0 // A test duration
        shapelayer.add(animation, forKey: "myAnimation")
    }

在上面的代码中你可以看到我只绘制了第一个字母。我将如何绘制其他字母?我需要为每个字母创建一个新的 CAShapeLayer 吗?这样做似乎效率低下。 CAShapeLayer 是否可以有多个 UIBezierPath 然后分别为它们设置动画?对此的任何提示将不胜感激!谢谢

您绝对可以使用单个 CAShapeLayer by combining multiple UIBezierPath using the append(_:) 实例方法。

代码看起来像这样:

private func animateSentData(data: WhiteboardData) {

    var path = UIBezierPath()
    for line in data.lines {
        let subPath = UIBezierPath()

        for (n, point) in line.pts.enumerated() {
            /// Construct your subPath
            …
        }
        path.append(subPath)
    }

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    …
}

澄清:

虽然您可以将多个路径合并为一个 UIBezierPath,但之后您不能为单个子路径设置动画。