"路径"使用CABasicAnimation制作动画 - 转动" x"选中标记

时间:2016-09-05 13:28:30

标签: swift core-animation

我想制作一个'变形'来自" x"选中标记:所以:

The start path

应该变成这个(动画):

enter image description here

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

enter image description here

然后这变成了复选标记。为什么?我该如何解决?或者这不适用于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")

1 个答案:

答案 0 :(得分:3)

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