【问题标题】:Gradient Animation - Slow down and speed up渐变动画 - 减速和加速
【发布时间】:2016-12-07 16:40:44
【问题描述】:

我正在为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:

为了让它看起来完全像我想要的那样,我需要使用CAMediaTimingFunction 吗?

【问题讨论】:

  • 你需要一个关键帧动画。
  • @JF 怎么样 - 我还会使用 CAGradientLayer 并将其与 CAKeyframeAnimation 结合使用吗?
  • 与您现在使用CABasicAnimation 的方式相同,但改为使用CAKeyframeAnimation
  • @JF 好的,我明白你的意思了。我以前使用过CAKeyframeAnimation,但那是沿着给定的pathUIView 进行动画处理。不知道如何将它与CAGradientLayer 一起使用。您能否显示一些代码或指向我的链接?谢谢

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


【解决方案1】:

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

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

【讨论】:

  • 谢谢!我试过了(稍微修改了一下)并更新了我的代码。关于CAMediaTimingFunction,我还有一个以上问题。
  • 非常感谢您的帮助! :)
  • 我似乎无法调整这些值以使其完美。能否请您看看我的新问题,谢谢:stackoverflow.com/questions/41032073/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-13
  • 2019-01-16
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
相关资源
最近更新 更多