创build一个类似于xCode中的Solar Weather Application的animation渐变背景

虽然我以前曾经问过这个问题,但我希望再次提出来澄清一下,在你的帮助下,我想完成什么。 我想知道如何在xCode中创build背景和iOS应用程序,类似于随着时间的推移(在一个周期中)稍微改变的Solar天气应用程序的背景(提供的截图)。 正如你所看到的,渐变非常平滑,显然包含两个以上的要点。 任何帮助示例或代码片段将不胜感激。 再次感谢,本。

截图1截图2

我需要的是:

  1. 添加CAGradientLayer到你的视图控制器(或自定义视图),例如:

     @property (nonatomic, retain) CAGradientLayer *gradient; 
  2. 在您的视图控制器中,在viewDidLoad中,创build渐变图层并将其添加到您的视图中:

     self.gradient = [CAGradientLayer layer]; gradient.frame = self.view.bounds; gradient.colors = [NSArray arrayWithObjects: (id)topColor.CGColor, (id)bottomColor.CGColor, nil]; gradient.locations = [NSArray arrayWithObjects: [NSNumber numberWithFloat:0.0f], [NSNumber numberWithFloat:0.7], nil]; [self.view.layer addSublayer:self.gradient]; 

    3A。 添加一个NSTimer到你的控制器,它会以适当的时间间隔更新self.gradient

      topColor = ...; bottomColor = ...; NSArray* newColors = [NSArray arrayWithObjects: (id)topColor.CGColor, (id)bottomColor.CGColor, nil]; [(CAGradientLayer *)self.layer setColors:newColors]; 

    这将允许您准确地决定在每个步骤中要使用哪种颜色的渐变。 否则,你可以尝试一个animation,像这样:

    3B。 添加这样的animation,

     - (void)animateLayer... { [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{ [CATransaction begin]; [CATransaction setAnimationDuration:duration]; topColor = ...; bottomColor = ...; NSArray* newColors = [NSArray arrayWithObjects: (id)topColor.CGColor, (id)bottomColor.CGColor, nil]; [(CAGradientLayer *)self.layer setColors:newColors]; [CATransaction commit]; } completion:^(BOOL b) { [self animateLayer..]; }]; } 

你也可以结合3a和3b。

简单的工作例子:

.h文件

 @property (strong, nonatomic) CAGradientLayer *gradient; 

.m文件

 - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear: animated]; self.gradient = [CAGradientLayer layer]; self.gradient.frame = self.view.bounds; self.gradient.colors = @[(id)[UIColor purpleColor].CGColor, (id)[UIColor redColor].CGColor]; [self.view.layer insertSublayer:self.gradient atIndex:0]; [self animateLayer]; } -(void)animateLayer { NSArray *fromColors = self.gradient.colors; NSArray *toColors = @[(id)[UIColor redColor].CGColor, (id)[UIColor orangeColor].CGColor]; [self.gradient setColors:toColors]; CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"colors"]; animation.fromValue = fromColors; animation.toValue = toColors; animation.duration = 3.00; animation.removedOnCompletion = YES; animation.fillMode = kCAFillModeForwards; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; animation.delegate = self; // Add the animation to our layer [self.gradient addAnimation:animation forKey:@"animateGradient"]; } 

您可能需要实施其他方法来移动颜色,然后重新进行更改。 但是,这应该可以帮助你到达那里。