简体   繁体   English

iphone:为CALayer子层设置动画

[英]iphone : animating a CALayer sublayer

I'm trying to animate the sublayer of a UIView's layer with the following code: 我正在尝试使用以下代码为UIView图层的子图层设置动画:

CALayer *sublayer = [[CALayer alloc] init];
[sublayer setFrame:myRect]; // myRect is a portion of the view's frame rectangle
[self.layer addSublayer:sublayer];

and later in my drawRect: method: 然后在我的drawRect:方法中:

CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"opacity"];
anim.duration = 1.0f;
anim.fromValue = [NSNumber numberWithFloat:1];
anim.toValue = [NSNumber numberWithFloat:.5];
anim.delegate = self;
[sublayer addAnimation:anim forKey:@"animateOpacity"];

I don't understand why my sublayer doesn't animate since the code [self.layer addAnimation:anim forKey:@"animateOpacity"]; 自代码[self.layer addAnimation:anim forKey:@"animateOpacity"];我不理解为什么我的子图层不设置动画[self.layer addAnimation:anim forKey:@"animateOpacity"]; does animate the view's main layer. 为视图的主层设置动画。

Thanks. 谢谢。

Don't add CAAnimation s during the drawRect: method. 不要在drawRect:方法中添加CAAnimation CoreAnimation calls it when it needs to redraw the content of the view (which could be at any time). 当需要重绘视图内容时(可能在任何时候),CoreAnimation都会调用它。 You should instead add the animation after the view has been added to its parent. 相反,应在将视图添加到其父级之后添加动画。

You can't animate the frame property. 您无法为frame属性设置动画。 Animate the bounds or position instead. 设置边界或位置的动画。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM