"path" 使用 CABasicAnimation 的动画 - 将 "x" 变成复选标记

"path" animation with CABasicAnimation - Turn "x" into a checkmark

我想将 'morph' 从 "x" 动画化为复选标记:所以这个:

应该变成这样(动画):

我分别创建了这些路径(请参阅下面的代码)但是当我尝试使用 CABasicAnimation 为它们设置动画时,我得到的是这个而不是开头的十字:

然后这变成了复选标记。为什么?我该如何解决?或者这不适用于 CABasicAnimation?

// just the blue background
    let shapeLayer = CAShapeLayer()
    shapeLayer.frame = CGRect(x: 0, y: 0, width: bounds.height, height: bounds.height)
    shapeLayer.backgroundColor = UIColor.blue.cgColor
    layer.addSublayer(shapeLayer)


    // first path (the "x")
    let padding: CGFloat = 10
    let crossPath = UIBezierPath()
    crossPath.move(to: CGPoint(x: padding, y: padding))
    crossPath.addLine(to: CGPoint(x: bounds.height - padding, y: bounds.height - padding))
    crossPath.move(to: CGPoint(x: bounds.height - padding, y: padding))
    crossPath.addLine(to: CGPoint(x: padding, y: bounds.height - padding))

    // Create the shape layer that will draw the path
    let signLayer = CAShapeLayer()
    signLayer.frame = bounds
    signLayer.path = crossPath.cgPath // setting the path from above
    signLayer.strokeColor = UIColor.white.cgColor
    signLayer.fillColor = UIColor.clear.cgColor
    signLayer.lineWidth = 4

    // add it to your view's layer and you're done!
    layer.addSublayer(signLayer)

    let anim: CABasicAnimation = CABasicAnimation(keyPath: "path")
    anim.duration = 10.0 // just a test value to see the animation more clearly

    // the checkmark
    let checkmarkPath = UIBezierPath()
    checkmarkPath.move(to: CGPoint(x: bounds.height - padding, y: padding))
    checkmarkPath.addLine(to: CGPoint(x: 2 * padding, y: bounds.height -  padding))
    checkmarkPath.addLine(to: CGPoint(x: padding, y: bounds.height / 2))

    anim.fromValue = crossPath.cgPath
    anim.toValue = checkmarkPath.cgPath

    signLayer.path = checkmarkPath.cgPath
    signLayer.add(anim, forKey: "path")

要正确设置动画,您需要在具有相同点数的 2 条路径之间设置动画。您的 crossPath 有 4 个点,checkmarkPath 有 3 个点。