2014-03-30 100 views
2

我有一個CAShapeLayer子類,它具有兩個屬性startPoint和endPoint。這些屬性不直接繪製到上下文中,而是用於改變路徑屬性,類似於變換,位置和邊界屬性。根據路徑屬性爲CAShapeLayer的子類自定義屬性設置動畫

這裏是整層

-(void)setStartPoint:(CGPoint)startPoint { 
    if (!CGPointEqualToPoint(_startPoint, startPoint)) { 
     _startPoint = startPoint; 

     [self reloadPath]; 
    } 
} 

-(void)setEndPoint:(CGPoint)endPoint { 
    if (!CGPointEqualToPoint(_endPoint, endPoint)) { 
     _endPoint = endPoint; 

     [self reloadPath]; 
    } 
} 

-(id)initWithLayer:(CRPathLayer*)layer { 
    self = [super initWithLayer:layer]; 
    if (self && [layer isKindOfClass:[CRPathLayer class]]) { 
     self.startPoint = layer.startPoint; 
     self.endPoint = layer.endPoint; 
    } 

    return self; 
} 

+(BOOL)needsDisplayForKey:(NSString *)key { 
    if ([key isEqualToString:NSStringFromSelector(@selector(startPoint))] || [key isEqualToString:NSStringFromSelector(@selector(endPoint))]) { 
     return YES; 
    } 

    return [super needsDisplayForKey:key]; 
} 

-(void)reloadPath { 
    CGMutablePathRef path = CGPathCreateMutable(); 
    CGPathMoveToPoint(path, NULL, self.startPoint.x, self.startPoint.y); 
    CGPathAddLineToPoint(path, NULL, self.endPoint.x, self.endPoint.y); 

    self.path = path; 
    CGPathRelease(path); 
} 

的代碼但是有一個問題。我需要爲兩個新屬性之一(start-或endPoint)設置動畫。我意識到我可以直接爲路徑屬性設置動畫,但這不是我想要實現的。 我很明顯在實現中缺少一些東西。當我嘗試使用CABasicAnimation對它進行動畫處理時,根本沒有任何反應。

有人可以幫我嗎? 在此先感謝。

回答

1

你缺少的作品是actionForKey:方法(雖然path是動畫的,但它不是隱含的動畫效果(即不會因爲屬性更改而不動畫))。

只要startPoint或endPoint更改(或者讓路徑隱式設置爲動畫,以便設置新路徑導致動畫,則爲路徑提供動作(動畫的更一般的術語)他們真的做同樣的事情)。

它可能看起來是這樣的(我在瀏覽器中,因此可能無法編譯輸入了這一點):

- (id <CAAction>)actionForKey:(NSString *)key 
{ 
    if ([key isEqualToString:@"startPoint"] || [key isEqualToString:@"endPoint")]) { 
     CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"path"]; 
     anim.fromValue = [self.presentationLayer valueFoKey:@"path"]; 
     return animo; 
    } 

    return [super valueForKey:key]; 
} 
+0

嗯,事實證明,actionForKey甚至沒有呼籲@「的startPoint」或@「端點「 – lbrndnr

+0

核心動畫喜歡它的屬性'@ dynamic'。你做到了嗎? –

+0

嗯,我已經嘗試過,但後來出現問題,我應該重新計算路徑。 – lbrndnr