CALayer连续循环中的梯度过渡

时间:2015-07-30 10:55:04

标签: ios swift

我打算在连续循环中从CALayer梯度过渡动画,即从colorOne到colorTwo,然后从ColorTwo到ColorOne。我已经能够只针对一个实例实现此逻辑,但不能持续实现。我该怎么做呢代码如下:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated);
    self.gradientOne = CAGradientLayer();
    self.gradientOne?.frame = self.view.bounds;
    self.gradientOne?.colors = [UIColor(red: 0.0/255.0, green: 150.0/255.0, blue: 123.0/255.0, alpha: 1.0).CGColor, UIColor(red: 0.0/255.0, green: 150.0/255.0, blue: 123.0/255.0, alpha: 1.0).CGColor]
    self.view.layer.insertSublayer(self.gradientOne, atIndex: 0)

            UIView.animateKeyframesWithDuration(3.0, delay: 0.0, options: UIViewKeyframeAnimationOptions.Repeat, animations: { () -> Void in

        UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 3.0, animations: { () -> Void in

            self.colorTimer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "animateLayerToGreen", userInfo: nil, repeats: true);
            self.animateLayerToBlue()
        })

    }, completion: nil)
}

func animateLayerToBlue(){

    var fromColors = self.gradientOne?.colors
    var toColors: [AnyObject] = [ UIColor.blueColor().CGColor, UIColor.blueColor().CGColor]
    self.gradientOne!.colors = toColors
    var animation : CABasicAnimation = CABasicAnimation(keyPath: "colors")

    animation.fromValue = fromColors
    animation.toValue = toColors
    animation.duration = 4.00
    animation.removedOnCompletion = true
    animation.fillMode = kCAFillModeForwards
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
    animation.delegate = self
    self.gradientOne?.addAnimation(animation, forKey:"animateGradient")
}

func animateLayerToGreen(){

    var fromColors = self.gradientOne?.colors
    var toColors: [AnyObject] = [UIColor(red: 0.0/255.0, green: 150.0/255.0, blue: 123.0/255.0, alpha: 1.0).CGColor, UIColor(red: 0.0/255.0, green: 150.0/255.0, blue: 123.0/255.0, alpha: 1.0).CGColor]
    self.gradientOne!.colors = toColors
    var animation : CABasicAnimation = CABasicAnimation(keyPath: "colors")

    animation.fromValue = fromColors
    animation.toValue = toColors
    animation.duration = 4.00
    animation.removedOnCompletion = true
    animation.fillMode = kCAFillModeForwards
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
    animation.delegate = self
    self.gradientOne?.addAnimation(animation, forKey:"animateGradient")
}

1 个答案:

答案 0 :(得分:2)

尝试设置:

 animation.repeatCount = Float.infinity
 animation.removedOnCompletion = false

希望它有效!