我在搞乱一个基本的 CAAnimation 示例,我只是想让 CALayer 在 UIView 的子类中旋转。我首先制作一个带有红色背景的新 CALayer 并将其插入 self.layer。然后,我制作了一个应该在不透明度更改时触发的 CAAnimation,并将其应用于 CALayer,之后它按预期旋转。
奇怪的是,如果我尝试使用 performSelector:withObject:afterDelay: 应用完全相同的动画,则 CALayer 不再动画,尽管它的不透明度仍然会发生变化。更奇怪的是,如果我使用 performSelector:withObject:afterDelay: 使用几乎相同的代码为 self.layer 设置动画,它就可以工作。
关于发生了什么的任何想法?这是我的代码:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
point = [[CAGradientLayer alloc] init];
point.backgroundColor = [UIColor redColor].CGColor;
point.bounds = CGRectMake(0.0f, 0.0f, 30.0f, 20.0f);
point.position = CGPointMake(100.0f, 100.0f);
[self.layer addSublayer:point];
[point release];
[self performSelector:@selector(test) withObject:nil afterDelay:2];
}
return self;
}
-(void)test {
[self spinLayer:point];
// [self spinLayer:self.layer]; works here
}
-(CAAnimation*)animationForSpinning {
CATransform3D transform;
transform = CATransform3DMakeRotation(M_PI/2.0, 0, 0, 1.0);
CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
basicAnimation.toValue = [NSValue valueWithCATransform3D:transform];
basicAnimation.duration = 5;
basicAnimation.cumulative = NO;
basicAnimation.repeatCount = 10000;
return basicAnimation;
}
-(void)spinLayer:(CALayer*)layer {
CAAnimation *anim = [self animationForSpinning];
[layer addAnimation:anim forKey:@"opacity"];
layer.opacity = 0.6;
}
这是我的界面
@interface MyView : UIView {
CALayer *point;
}
-(void)test;
-(void)spinLayer:(CALayer*)layer;
-(CAAnimation*)animationForSpinning;
@end
注意:我正在使用等于[UIScreen mainScreen].applicationFrame
来自应用程序委托的框架实例化此视图。