ios - 渐变动画——减速和加速

标签 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

最佳答案

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

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 中的每个元素传递的动画百分比,以反射(reflect)动画的当前状态。这也应该与 values 具有相同的长度。

我实际上并不了解 Swift,所以这应该有效,但我不能保证。

关于ios - 渐变动画——减速和加速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41022824/

相关文章:

ios - 旋转 iPad 时自定义警报 View 会导致崩溃

ios - 如何使用我的 iOS 应用程序在我的 iPad/iPhone 中打开 PDF 文件?

objective-c - 调用-[NSFileManager setUbiquitous :itemAtURL:destinationURL:error:] never returns

ios - 带有 UITableViewAutomaticDimension 的 UITableViewCell rowHeight 不适用于计算自动布局

ios - 带有 reloadData 的 AKPickerView 导致奇怪的行为

iphone - 匹配字符串格式

ios - 使用 IB_DESIGNABLE obj-c 扩展类

iOS - 如何在不初始化 Swift 类的情况下调用方法?

arrays - swift 遵循 Stridable 后进入死循环

ios - 需要 iOS 版 Stripe API 来传递信用卡详细信息