ios - 如何在动画过程中改变 CALayer 的颜色?

标签 ios objective-c calayer

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

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,而且它允许对动画进行更多控制。

//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];

关于ios - 如何在动画过程中改变 CALayer 的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16205089/

相关文章:

ios - 如何使用 PSPDFKit 检查后台线程中使用主线程代码?

ios - 在子类中根据 UIButton 大小设置 cornerRadius 的最佳位置?

ios - 反转基于描边的 CALayer 蒙版(无填充)

iOS 8 Beta 4 CLLocationManager 不工作 Placemark null

ios - 将值从 Objective-C 传递到 JS 文件

ios - iCloud:NSUbiquitousKeyValueStore 问题

iphone - iPhone SDK上的JSON解析

ios - 在 parse.com 上存储消息传递应用程序的发送消息历史记录?

objective-c - map 套件 : add MKPolyline hide MKTileOverlay

ios - 如何用另一个透明的 CALayer 遮盖 CALayer?