Animating CALayer's shadowPath property

后端 未结 3 690
滥情空心
滥情空心 2020-12-10 05:16

I am aware that a CALayer\'s shadowPath is only animatable using explicit animations, however I still cannot get this to work. I suspect that I am not passing the toVa

相关标签:
3条回答
  • 2020-12-10 05:29

    I've met same problem for shadow animation and find solution for persisting shadow after end of animation. You need to set final path to your shadow layer before you start animation. Reverting to initial shadow happens because CoreAnimation does not update properties of original layer, it creates copy of this layer and display animation on this copy (check Neko1kat answer for more details). After animation ended system removes this animated layer and return original layer, that has not updated path and your old shadow appears. Try this code:

        let shadowAnimation = CABasicAnimation(keyPath: "shadowPath")
        shadowAnimation.fromValue = currentShadowPath
        shadowAnimation.toValue = newShadowPath
        shadowAnimation.duration = 3.0
    
        shadowLayer.shadowPath = newShadowPath
        shadowLayer.add(shadowAnimation, forKey: "shadowAnimation")
    
    0 讨论(0)
  • 2020-12-10 05:30

    Firstly, you did not set the animation's fromValue.

    Secondly, you're correct: toValue accepts a CGPathRef, except it needs to be cast to id. Do something like this:

    theAnimation.toValue = (id)[UIBezierPath bezierPathWithRect:newRect].CGPath;
    

    You'll also need to set the shadowPath property of the layer explicitly if you want the change to remain after animation.

    0 讨论(0)
  • 2020-12-10 05:30
    let cornerRadious = 10.0
            //
            let shadowPathFrom = UIBezierPath(roundedRect: rect1, cornerRadius: cornerRadious)
            let shadowPathTo = UIBezierPath(roundedRect: rect2, cornerRadius: cornerRadious)
            //
            layer.masksToBounds = false
            layer.shadowColor = UIColor.yellowColor().CGColor
            layer.shadowOpacity = 0.6
            //
            let shadowAnimation = CABasicAnimation(keyPath: "shadowPath")
            shadowAnimation.fromValue = shadowPathFrom.CGPath
            shadowAnimation.toValue = shadowPathTo.CGPath
            shadowAnimation.duration = 0.4
            shadowAnimation.autoreverses = true
            shadowAnimation.removedOnCompletion = true
            shadowAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
            layer.addAnimation(shadowAnimation, forKey: "shadowAnimation")
    
    0 讨论(0)
提交回复
热议问题