如何在CALayer中为UIColor设置动画? [英] How can I animate a UIColor in a CALayer?
问题描述
我有一个自定义CALayer,在其中尝试使用 actionForKey 并遵循本教程。
I have a custom CALayer within which I'm trying to enable the animation of certain properties using actionForKey and following this tutorial.
我有一个 CGFloat
属性,当放置在里面时,它会完美地改变一个动画块,但我的其他属性 UIColor
不会。
I have a CGFloat
property that will change perfectly when inside an animation block but my other property, a UIColor
, will not.
这是我的功能:
- (id<CAAction>)actionForKey:(NSString *)event {
if ([self presentationLayer] != nil && [[self class] isCustomAnimationKey:event]) {
id animation = [super actionForKey:@"backgroundColor"];
if (animation == nil || [animation isEqual:[NSNull null]]) {
[self setNeedsDisplay];
return [NSNull null];
}
[animation setKeyPath:event];
[animation setFromValue:[self.presentationLayer valueForKey:event]];
[animation setToValue:nil];
return animation;
}
return [super actionForKey:event];
}
使用 CGContextSetFillColorWithColor $设置颜色c $ c>,但我从日志中看到颜色只是简单地从一种颜色更改为另一种颜色,而没有任何内插值。
The colour is being set using CGContextSetFillColorWithColor
but I can see from logs that the colour simply changes from one to the next without any of the interpolated values.
有什么想法吗?
推荐答案
最后发现很明显,我需要公开一个 CGColor
属性在我的CALayer中进行动画处理。
It turned out to be obvious in the end, I needed to expose a CGColor
property in my CALayer and animate that instead.
编辑:
下面是一些使用的代码href = https://github.com/MrNickBarker/UIViewCustomPropertyAnimation rel = nofollow noreferrer> UIViewCustomPropertyAnimation 项目作为基础。
Here's some code for this, using the UIViewCustomPropertyAnimation project as a basis.
在 OCLayer.h
添加新属性:
@property (nonatomic) CGColorRef myColor;
在 OCLayer.m
中添加@dynamic指令:
In OCLayer.m
add the @dynamic directive:
@dynamic myColor;
并更新 isCustomAnimKey
:
+ (BOOL)isCustomAnimKey:(NSString *)key {
return [key isEqualToString:@"percent"] || [key isEqualToString:@"myColor"];
}
在 OCView.h
添加相同的属性,但添加为 UIColor
。这已经存在于我的项目中,因此不需要修改,这很棒,因为它没有破坏任何代码。
In OCView.h
add the same property but as a UIColor
. This already existed in my project so didn't require modification, which is great because it didn't break any code.
@property (nonatomic, strong) UIColor *progressColor;
主要更改将在 OCView.m
作为获取器和设置器,需要将 CGColor
转换为 UIColor
并再次返回。
The main changes would be in OCView.m
as the getter and setter need to convert from CGColor
to UIColor
and back again.
- (void)setMyColor:(UIColor *)color {
self.layer.myColor = color.CGColor;
}
- (UIColor*)myColor {
return [UIColor colorWithCGColor: self.layer.myColor];
}
现在可以正常执行动画了:
The animation can now be carried out as normal:
[UIView animateWithDuration:1.f animations:^{
self.animView.myColor = [UIColor redColor];
}];
这篇关于如何在CALayer中为UIColor设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!