渐变动画 - 慢下来并加快速度 [英] Gradient Animation - Slow down and speed up

查看:104
本文介绍了渐变动画 - 慢下来并加快速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设置一个 CAGradientLayer 的动画,类似于Apple在iPhone主屏幕上的Slide to Unlock动画。然而,我的动画有点不同,它在某些点上减速并加速。

I'm animating a CAGradientLayer, similar to how Apple did with their "Slide to Unlock" animation on the home screen of iPhone. However my animation is a little different in that it slows down and speeds up at certain points.

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

The code I have so far is animates a gradient and works, but how would I get it to slow down/speed up at different points?

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 吗?

To make it look exactly like I want, would I need to use CAMediaTimingFunction at all?

推荐答案

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

To use a keyframe animation, try:

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

This will go between the three times equally. To change the times at which the keyframes occur, set keyTimes:

gradientAnimation.keyTimes = [0.0, 0.4, 1.0]

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

This will set the percentage of the animation should be passed for each element in values to reflect the current state of the animation. This should also have the same length as values.

我实际上并不知道Swift,所以这个应该工作,但我无法保证。

I don’t actually know Swift, so this should work, but I can’t guarantee it.

这篇关于渐变动画 - 慢下来并加快速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆