动画自定义CALayer属性

时间:2010-07-03 07:45:50

标签: iphone core-animation calayer

我正在尝试根据现有的图层属性位置定义一个抽象图层属性angle。基本上它描述了从圆心开始的层的方向。我确实喜欢以下内容:

@interface MenuItemLayer : CALayer
  @property CGFloat angle;
@end

@implementation MenuItemLayer

+ (BOOL)needsDisplayForKey: (NSString*)key {
  if ([key isEqualToString: @"angle"]) return YES;
  return [super needsDisplayForKey: key];
}

- (void)drawInContext: (CGContextRef)context {
  [self renderInContext: context];
}

- (CGFloat)angle {
  CGPoint center = self.superlayer.center;
  CGPoint pos = self.position;
  return atan2f(pos.x - center.x, center.y - pos.y);
}

- (void)setAngle: (CGFloat)angle {
  CGPoint center = self.superlayer.center;
  CGFloat radius = 100;
  [CATransaction begin];
  [CATransaction setDisableActions: YES];
  self.position = CGPointMake(center.x + radius * sinf(angle),
                              center.y - radius * cosf(angle));
  [CATransaction commit];
}

@end


当我使用setAngle:手动设置值时,它工作正常,但问题是,当我尝试使用CABasicAnimation为其设置动画时,MenuItemLayer维持的视图根本不会移动并保持在原始位置,而我可以看到setValue:和drawInContext:正常调用动画的进度,因此表示层的位置属性得到更新。

有人有一些线索吗?谢谢!



----

在文档中注意到以下注释:

renderInContext:
This method renders directly from the layer tree, ignoring any animations added to the render tree. Renders in the coordinate space of the layer.


这是否意味着即使在drawInContext:方法的接收器是表示层的情况下,renderInContext:也总是使用模型层来渲染图像?这可能是问题的原因吗?如果是这样,我是否应该始终手动将图层转换为表示层所代表的正确位置?

1 个答案:

答案 0 :(得分:0)

你打算做什么?

- (void)drawInContext: (CGContextRef)context {
  [self renderInContext: context];
}

当你评论出来时会发生什么?我发现-renderInContext最常用于渲染到上下文中,以便将其保存为图像,所以这对我来说很奇怪。一个基本的动画应该能够没有问题地动画你的属性,但重写-drawInContext似乎只有你计划用CG做一些自定义绘图才有意义。