2012-10-08 69 views
2

我有一些UIView的用的drawRect代碼繪製餅:動畫效果Circle的endAngle與CABasicAnimation

- (void)drawRect:(CGRect)rect 
    { 
     CGRect parentViewBounds = self.bounds; 
     CGFloat x = CGRectGetWidth(parentViewBounds)/2; 
     CGFloat y = CGRectGetHeight(parentViewBounds)/2; 

     // Get the graphics context and clear it 
     CGContextRef ctx = UIGraphicsGetCurrentContext(); 
     CGContextClearRect(ctx, rect); 


     // define line width 
     CGContextSetLineWidth(ctx, 4.0); 


     CGContextSetFillColor(ctx, CGColorGetComponents([someColor CGColor])); 
     CGContextMoveToPoint(ctx, x, y); 
     CGContextAddArc(ctx, x, y, 100, radians(270), radians(270), 0); // 27 
     CGContextClosePath(ctx); 
     CGContextFillPath(ctx); 
} 

但是,當我嘗試動畫繪製後「endAngle」屬性,這是行不通的:

CABasicAnimation *theAnimation; 
theAnimation=[CABasicAnimation animationWithKeyPath:@"endAngle"]; 
theAnimation.duration=1; 
theAnimation.repeatCount=1; 
theAnimation.autoreverses=NO; 
theAnimation.fromValue=[NSNumber numberWithFloat:270]; 
theAnimation.toValue=[NSNumber numberWithFloat:60]; 
[[self.layer presentationLayer] addAnimation:theAnimation forKey:@"animateLayer"]; 

我在哪裏犯錯?

回答

1

幾件事情。您不能使用CAAnimation爲您在drawRect方法中執行的繪圖設置動畫效果。其次,如果您確實使用了CAShapeLayer,則可以對安裝在圖層中的路徑進行動畫更改,但您需要確保該路徑具有與動畫中所有步驟相同的控制點數量和類型。

CGPath弧命令使用不同數量的控制點繪製不同的角度。因此,您無法更改弧的角度併爲其生成動畫。

你需要做的是安裝一個完整弧長的路徑,然後爲shape層的strokeStart和/或strokeEnd屬性設置動畫變化。這些屬性導致路徑從圖形中省略路徑的第一部分/最後部分。我敢說大衛在動畫餅圖中所使用的教程使用了這種技術。