渐变动画——减速和加速

Gradient Animation - Slow down and speed up

我正在为 CAGradientLayer 制作动画,类似于 Apple 在 iPhone 的主屏幕上制作 "Slide to Unlock" 动画的方式。然而,我的动画有点不同,它会在某些点减慢速度。

我目前的代码是动画渐变并且有效,但我如何让它在不同的点减慢 down/speed?

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:

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

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

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,所以这个应该有效,但我不能保证。