尽管我之前已经问过这个问题,但我想再次联系你以澄清我希望通过你的帮助实现什么。我想知道如何在xCode中创建一个类似于Solar天气应用程序(提供了截屏)的背景,它会随着时间的推移略微变化(循环)。正如您所看到的渐变非常平滑,显然包含不止两个主要点。非常感谢任何带有示例或代码片段的帮助。再次感谢,Ben。
我需要的是:
将 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];
这将允许您准确决定每个步骤中要使用的渐变色。否则,您可以尝试像这样添加动画:- (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"];
}
你可能想要实现一个额外的方法来改变颜色,然后重新运行动画以呈现变化。但这应该会帮助你实现目标。
self.gradient.colors = toColors
- TheTigerviewDidAppear
中调用 super
也是一个很好的实践。 - smaili