代码之家  ›  专栏  ›  技术社区  ›  Joseph

减缓CAGradientLayer动画

  •  0
  • Joseph  · 技术社区  · 7 年前

    我想制作一个三色渐变的动画 慢速地 .

    我有一个习惯 UIView 像这样:

    class MyView: UIView, CAAnimationDelegate {
    
      lazy var gradientLayer: CAGradientLayer = {
            let l = CAGradientLayer()
            l.frame = self.frame
            l.colors = self.colors
            l.startPoint = CGPoint(x: 0, y: 0)
            l.endPoint = CGPoint(x: 1, y: 0)
            l.mask = self.textLayer
            return l
        }()
    
        lazy var textLayer: CATextLayer = {
            let l = CATextLayer()
            l.frame = self.frame
            l.string = "test".uppercased()
            l.fontSize = 23
            return l
        }()
    
        var colors: [CGColor] =  [
                UIColor.red.cgColor,
                UIColor.purple.cgColor,
                UIColor.blue.cgColor
                ]
    
        init() {
        ...
        self.layer.addSublayer(gradientLayer)
    
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        func animate() {
    
          var newColors = colors
          let lastColor: CGColor = newColors.last!
          newColors.removeLast()
          newColors.insert(lastColor, at: 0)
    
          colors: newColors
          gradientLayer.colors = newColors
    
          let a = CABasicAnimation(keyPath:"colors")
          a.toValue = newColors
          a.duration = 0.1
          a.isRemovedOnCompletion = true
          a.fillMode = kCAFillModeForwards
          a.delegate = self
    
          gradientLayer.add(a, forKey:"animateGradient")
    
        }
    
        func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
    
              animate()
        }
    
    }
    

    这是可行的,但速度非常快。我怎样才能减缓动画的速度,而不让它变得阻塞? 我必须给这个添加几百种颜色吗 colors 数组,使其有足够的循环通过?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Marcus    7 年前

    func animate() {
      let oldColors = colors
      var newColors = colors
      let lastColor: CGColor = newColors.last!
      newColors.removeLast()
      newColors.insert(lastColor, at: 0)
    
      colors = newColors
      gradientLayer.colors = newColors
    
      let a = CABasicAnimation(keyPath:"colors")
      // New line here ->
      a.fromValue = oldColors
      a.toValue = newColors
      a.duration = 0.1
      a.isRemovedOnCompletion = true
      a.fillMode = kCAFillModeForwards
      a.delegate = self
    
      gradientLayer.add(a, forKey:"animateGradient")
    
    }
    

    这将是您没有真正获得动画的原因-您的代码被有效地设置为创建延迟的捕捉转换。