2010-07-03 193 views
2

我想根據現有圖層屬性位置定義抽象圖層屬性角度。基本上它描述了從一個圓的中心的層的方向。我不喜歡以下內容:動畫自定義CALayer屬性

@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:會隨着動畫的進度而正常調用,因此表示層的position屬性會更新。

任何人都有一些線索?謝謝!



----

只注意到在doc以下注釋:

 
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.


這是否意味着renderInContext:將始終使用模型層呈現圖像,即使在我們的情況下,drawInContext:方法的接收者是表示層?這可能是問題的原因嗎?如果是這樣,我應該總是手動將圖層轉換到表示層所代表的正確位置?

回答

0

你打算怎麼做?

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

當你評論它時會發生什麼?我發現-renderInContext最常用於渲染到上下文中,以便將它保存爲圖像,所以這對我來說看起來很奇怪。一個基本的動畫應該能夠動畫你的屬性沒有問題,但覆蓋-drawInContext似乎只有在你打算用CG做一些自定義繪圖時纔有意義。

+0

感謝您的回答。如果我刪除了drawInContext:這是很自然的,因爲我使用needsDisplayForKey機制來通知CA框架我的圖層應該被重畫。我打算renderInContext只是用動畫屬性值重繪圖層。 – Kay 2010-07-04 07:05:18

+0

你能否更新你的答案並向我展示你的CABasicAnimation代碼?您是否期望您對角度定製屬性進行更改以使位置動畫?這有兩個問題。一個是你已經禁用了這些動作,所以改變位置不會動畫。其次是我相信如果你想動畫兩個屬性(一個自定義,角度和一個位置),你使用兩個獨立的動畫和一個動畫組。除了我想你想讓你的位置根據角度的改變來改變和設置動畫,對吧? – 2010-07-05 16:58:30