2

我有一些带有 drawrect 代码的 UIView 用于绘制饼图:

    - (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"];

我在哪里犯错?

4

2 回答 2

2

如果你想制作动画,那么你应该考虑使用 Core Animation 进行绘图。它使动画更简单。

看看这个关于使用 Core Animation 制作自定义动画饼图的精彩教程。我相信你可以修改它以获得你想要的。

如果它对您来说似乎很复杂,那么您可以看看我对“画圆的一部分”的回答,它通过画一个非常宽的圆笔画来绘制饼图形状。

于 2012-10-08T19:58:04.807 回答
1

几件事。您不能使用 CAAnimation 来为您在 drawRect 方法中执行的绘图设置动画。

其次,如果您确实使用了 CAShapeLayer,您可以对安装在层中的路径进行动画更改,但您需要确保该路径对于动画中的所有步骤具有相同数量和类型的控制点。

CGPath arc 命令使用不同数量的控制点来绘制不同的角度。因此,您无法更改圆弧的角度并为其设置动画。

您需要做的是安装一条全长弧的路径,然后对形状图层的 strokeStart 和/或 strokeEnd 属性进行动画更改。这些属性会导致路径从图形中省略路径的第一部分/最后一部分。我敢说大卫链接到动画饼图的教程使用了这种技术。

于 2012-10-08T20:36:26.493 回答