如何在动画过程中更改CALayer的颜色? [英] How to change the color of CALayer during animation?

查看:76
本文介绍了如何在动画过程中更改CALayer的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望图层从绿色开始,然后从缓慢到黄色,橙色,最后是红色。我该怎么做?

I want the layer to start from green, then slowly to yellow, orange and finally red. How do I do this?

CAShapeLayer *layer = [CAShapeLayer layer];
[layer setStrokeColor:[UIColor greenColor].CGColor];
[layer setLineWidth:5.0f];
[layer setFillColor:[UIColor clearColor].CGColor];

UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:button.bounds cornerRadius:10.0f];
layer.path = path.CGPath;

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
animation.fromValue = [NSNumber numberWithFloat:0.0f];
animation.toValue = [NSNumber numberWithFloat:1.0f];
animation.duration = 4.0f;

[layer addAnimation:animation forKey:@"myStroke"];
[button.layer addSublayer:layer];


推荐答案

我刚刚为您编写了这段代码。我使用CAKeyframeAnimation既是因为它允许多个 toValues ,又是因为它允许对动画进行更多控制。

I just wrote up this code for you. I used a CAKeyframeAnimation both because it allows for multiple toValues and because it allows more control over the animation.

//Set up layer and add it to view
CALayer *layer = [CALayer layer];
layer.frame = self.view.bounds;
[self.view.layer addSublayer:layer];

//Create animation
CAKeyframeAnimation *colorsAnimation = [CAKeyframeAnimation animationWithKeyPath:@"backgroundColor"];
colorsAnimation.values = [NSArray arrayWithObjects: (id)[UIColor greenColor].CGColor,
                          (id)[UIColor yellowColor].CGColor, (id)[UIColor orangeColor].CGColor, (id)[UIColor redColor].CGColor, nil];
colorsAnimation.keyTimes = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.25], [NSNumber numberWithFloat:0.5], [NSNumber numberWithFloat:0.75],[NSNumber numberWithFloat:1.0], nil];
colorsAnimation.calculationMode = kCAAnimationPaced;
colorsAnimation.removedOnCompletion = NO;
colorsAnimation.fillMode = kCAFillModeForwards;
colorsAnimation.duration = 3.0f;

//Add animation
[layer addAnimation:colorsAnimation forKey:nil];

这篇关于如何在动画过程中更改CALayer的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆