渐变动画 - 慢下来并加快速度

时间:2016-12-07 16:40:45

标签: ios objective-c swift core-animation cagradientlayer

我为CAGradientLayer制作动画,类似于Apple使用他们的"幻灯片解锁" iPhone主屏幕上的动画。然而,我的动画有点不同,它在某些点上减速并加速。

我到目前为止的代码是动画渐变并且有效,但是如何让它在不同的点上减速/加速呢?

class AnimatedMaskLabel: UIView {

    let gradientLayer: CAGradientLayer = {
    let gradientLayer = CAGradientLayer()
        // Configure the gradient here
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)

        let colors = [
            UIColor.black.cgColor,
            UIColor.white.cgColor,
            UIColor.black.cgColor
        ]
        gradientLayer.colors = colors

        let locations: [NSNumber] = [0.0, 0.5, 1.0]
        gradientLayer.locations = locations

        return gradientLayer
    }()

  @IBInspectable var text: String! {
    didSet {
      setNeedsDisplay()
    }
  }

  override func layoutSubviews() {
    layer.borderColor = UIColor.green.cgColor
    gradientLayer.frame = bounds
  }

  override func didMoveToWindow() {
    super.didMoveToWindow()

    layer.addSublayer(gradientLayer)

    let gradientAnimation = CABasicAnimation(keyPath: "locations")
    gradientAnimation.fromValue = [0.0, 0.0, 0.25]
    gradientAnimation.toValue = [0.75, 1.0, 1.0]
    gradientAnimation.duration = 3.0
    gradientAnimation.repeatCount = Float.infinity
    gradientLayer.add(gradientAnimation, forKey: nil)
  }

}

更新1:

enter image description here

为了让它看起来像我想要的那样,我是否需要使用CAMediaTimingFunction

1 个答案:

答案 0 :(得分:2)

要使用关键帧动画,请尝试:

let gradientAnimation = CAKeyframeAnimation(keyPath: "locations")
gradientAnimation.values = [[0.0, 0.0, 0.25], [0.375, 0.5, 0.625], [0.75, 1.0, 1.0]]
gradientAnimation.duration = 3.0
gradientAnimation.repeatCount = Float.infinity
gradientLayer.add(gradientAnimation, forKey: nil)

这将平均三次之间。要更改关键帧出现的时间,请设置keyTimes

gradientAnimation.keyTimes = [0.0, 0.4, 1.0]

这将设置应为values中的每个元素传递的动画的百分比,以反映动画的当前状态。这也应该与values具有相同的长度。

我实际上并不认识Swift,所以工作,但我无法保证。