Swift中的CoreAnimation和CAReplicatorLayer?

时间:2016-04-17 17:41:48

标签: ios swift core-animation careplicatorlayer

我将这个库从objc移植到Swift,我在找出复制器层instanceCount没有对动画做任何事情时遇到问题。有什么想法吗?

如果您查看库,它会同时为该图层设置多个动画实例,但在我的代码中,一次只有一个图层动画。

https://github.com/shu223/PulsingHalo/blob/master/PulsingHalo/PulsingHaloLayer.m

public class PulsingHaloLayer2: CAReplicatorLayer {

    var fromValueForRadius: Float = 0.0
    var fromValueForAlpha: Float = 0.45
    var keyTimeForHalfOpacity: Float = 0.2
    var animationDuration: NSTimeInterval = 3.0
    var pulseInterval: NSTimeInterval = 0.0
    var useTimingFunction: Bool = true
    let animationGroup: CAAnimationGroup = CAAnimationGroup()
    var repetitions: Float = Float.infinity
    var radius: CGFloat = 200.0 {
        didSet {
            let tempPos = position
            let diameter = radius * 2

            bounds = CGRect(x: 0.0, y: 0.0, width: diameter, height: diameter)
            cornerRadius = radius
            position = tempPos
        }
    }
    var haloLayerNumber: Int = 4 {
        didSet {
            instanceCount = 4
            instanceDelay = (animationDuration + pulseInterval) / Double(haloLayerNumber)
        }
    }

    override init() {
        super.init()
        contentsScale = UIScreen.mainScreen().scale
        opacity = 0.0
        backgroundColor = UIColor.blueColor().CGColor
        haloLayerNumber = 4

        setupAnimationGroup()
        addAnimation(animationGroup, forKey: "pulse")
    }

    required public init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupAnimationGroup() {
        animationGroup.duration = animationDuration + pulseInterval
        animationGroup.repeatCount = repetitions
        animationGroup.removedOnCompletion = false

        if useTimingFunction {
            let defaultCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
            animationGroup.timingFunction = defaultCurve
        }

        let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
        opacityAnimation.duration = animationDuration
        opacityAnimation.values = [fromValueForAlpha, 0.45, 0]
        opacityAnimation.keyTimes = [0, keyTimeForHalfOpacity, 1]

        let scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy")
        scaleAnimation.fromValue = fromValueForRadius
        scaleAnimation.toValue = 1
        scaleAnimation.duration = animationDuration

        animationGroup.animations = [opacityAnimation, scaleAnimation]
    }

}

1 个答案:

答案 0 :(得分:3)

当您致电haloLayerNumber = 4时,会触发didSet阻止,因为它会在init内发生。

您可以使用闭包来解决此问题:({ haloLayerNumber = 4 })()。或者,您可以从instanceCount内部手动更新instanceDelay / init