我正在使用块代码创建一个反映一些数据的水平进度条,数据可以是任何东西。它只需要一个最小值,一个最大值和一个允许我设置动画的当前值,即最小值0,最大值100,当前值50,进度条将填满50%。我有一个进度条容器,里面有一个视图,视图在动画时被拉伸。
我使用块代码使动画部分正常工作,即
[UIView animateWithDuration:3.0
delay:0.0f
options:UIViewAnimationCurveEaseInOut
animations:^(void)
{
progressView.frame = CGRectMake(progressView.frame.origin.x,progressView.frame.origin.y,iWidth,progressView.frame.size.height);
}
completion:^(BOOL finished)
{
}];
我想做的是在动画时,通过插入子图层慢慢改变渐变,快速示例
(This method will be called on a timer, the idea is to slowly change the gradient
after 0.5 seconds for example)
CAGradientLayer *testLayer = [BackgroundLayer customGradient:iRedValue :iGreenValue :0];
testLayer.frame = progressView.bounds;
[progressView.layer insertSublayer:testLayer atIndex:1];
(背景图层只是我自定义的一个类,它允许用户使用RGB值创建自定义渐变颜色)。我的想法是,当progressView完成动画时,我会继续插入子图层,慢慢地改变渐变。这个想法是视图从一种颜色开始,比如绿色,并且沿着条形图进一步动画,它将颜色变为琥珀色,如果达到最大值则变为红色。
当我添加子图层时,动画只会跳到最后,因为testLayer在完成动画制作后会占用progressView的宽度,然后添加它。我想在动画过程中慢慢发生这种情况。
关于如何做到这一点的任何想法?
提前致谢!
答案 0 :(得分:2)
colors
CAGradientLayer
的小例子
@interface GradientAnimationView : UIView
@end
@implementation GradientAnimationView {
NSArray *_colorsFirst;
NSArray *_colorsSecond;
NSArray *_currentColor;
}
+ (Class)layerClass {
return [CAGradientLayer class];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
CAGradientLayer *layer = (CAGradientLayer *)[self layer];
_colorsFirst = @[(__bridge id)[[UIColor blueColor] CGColor], (__bridge id)[[UIColor greenColor] CGColor]];
_colorsSecond = @[(__bridge id)[[UIColor redColor] CGColor], (__bridge id)[[UIColor yellowColor] CGColor]];
_currentColor = _colorsFirst;
[layer setColors:_colorsFirst];
}
return self;
}
- (void)animateColors {
if (_currentColor == _colorsSecond) {
_currentColor = _colorsFirst;
} else {
_currentColor = _colorsSecond;
}
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"colors"];
anim.fromValue = [[self layer] valueForKey:@"colors"];
anim.toValue = _currentColor;
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
anim.duration = 0.4;
anim.delegate = self;
[self.layer addAnimation:anim forKey:@"colors"];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self animateColors];
}
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
CAGradientLayer *layer = (CAGradientLayer *)[self layer];
[layer setColors:_currentColor];
}
@end