尽管我之前已经提过这个问题,但我想再次联系以澄清我希望在你的帮助下完成的事情。我想知道如何在xCode中创建iOS应用程序的背景,类似于Solar天气应用程序(提供的屏幕截图)的背景,随着时间的推移(在一个周期中)略有变化。如您所见,渐变非常平滑,显然包含两个以上的要点。 任何有关代码示例或代码片段的帮助都将非常感激。再次感谢Ben。
答案 0 :(得分:16)
我需要的是:
将CAGradientLayer
添加到视图控制器(或自定义视图),例如:
@property (nonatomic, retain) CAGradientLayer *gradient;
在视图控制器的viewDidLoad中,创建渐变图层并将其添加到视图中:
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];
这将允许您准确地确定每个步骤中要用于渐变的颜色。否则,您可以尝试动画,如下所示:
3B。像这样添加动画,
- (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组合在一起。
答案 1 :(得分:13)
简单的工作示例:
.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"];
}
您可能希望实现一种其他方法来移动颜色,然后恢复更改。但这应该可以帮助你实现目标。