问题描述
我正在尝试构建一个 CABasicAnimation 来为 Core Animation CALayer 的 backgroundColor 属性设置动画,但我不知道如何正确包装 CGColorRef 值以传递给动画.例如:
I'm trying to construct a CABasicAnimation to animate the backgroundColor property of a Core Animation CALayer, but I can't figure out how to properly wrap a CGColorRef value to pass to the animation. For example:
CGColorSpaceRef rgbColorspace = CGColorSpaceCreateDeviceRGB();
CGFloat values[4] = {1.0, 0.0, 0.0, 1.0};
CGColorRef red = CGColorCreate(rgbColorspace, values);
CGColorSpaceRelease(rgbColorspace);
CABasicAnimation *selectionAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
[selectionAnimation setDuration:0.5f];
[selectionAnimation setToValue:[NSValue valueWithPointer:red]];
[layer addAnimation:selectionAnimation forKey:@"selectionAnimation"];
似乎对 backgroundColor 属性没有任何作用,我认为是因为将它作为包裹在 NSValue 中的指针传递不是传递它的方式.
seems to do nothing to the backgroundColor property, I assume because handing it off as a pointer wrapped in an NSValue is not the way to pass it along.
backgroundColor 是 CALayer 的一个动画属性,所以我的问题是:你如何设置这个特定属性的 From 或 To 值(最好以与 Mac/iPhone 平台无关的方式)?
backgroundColor is an animatable property of CALayer, so my question is: how do you set the From or To values for this particular property (preferably in a Mac / iPhone platform-independent way)?
推荐答案
在设置 toValue
或 fromValueCGColorRef
sCABasicAnimation
的/code> 属性.只需使用 CGColorRef
.为避免编译器警告,您可以将 CGColorRef
转换为 id
.
You don't need to wrap CGColorRef
s when setting the toValue
or fromValue
properties of a CABasicAnimation
. Simply use the CGColorRef
. To avoid the compiler warning, you can cast the CGColorRef
to an id
.
在我的示例应用中,以下代码将背景设置为红色.
In my sample app, the following code animated the background to red.
CABasicAnimation* selectionAnimation = [CABasicAnimation
animationWithKeyPath:@"backgroundColor"];
selectionAnimation.toValue = (id)[UIColor redColor].CGColor;
[self.view.layer addAnimation:selectionAnimation
forKey:@"selectionAnimation"];
但是,当动画结束时,背景会恢复到原来的颜色.这是因为 CABasicAnimation
只在动画运行时影响目标层的表现层.动画完成后,模型层中设置的值返回.因此,您还必须将图层 backgroundColor
属性设置为红色.也许使用 CATransaction
关闭隐式动画.
However, when the animation is over, the background returns to the original color. This is because the CABasicAnimation
only effects the presentation layer of the target layer while the animation is running. After the animation finishes, the value set in the model layer returns. So you are going to have to set the layers backgroundColor
property to red as well. Perhaps turn off the implicit animations using a CATransaction
.
首先,您可以通过使用隐式动画来省去这个麻烦.
You could save yourself this trouble by using an implicit animation in the first place.
这篇关于你如何明确地为 CALayer 的 backgroundColor 设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!