Swift 中的 CoreAnimation 和 CAReplicatorLayer?

CoreAnimation and CAReplicatorLayer in Swift?

我正在将此库从 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]
    }

}

当您调用 haloLayerNumber = 4 时,这 不会 触发 didSet 块,因为它发生在 init.[=17 内部=]

您可以使用闭包解决此问题:({ haloLayerNumber = 4 })()。或者您可以从 init.

内部手动更新 instanceCount/instanceDelay