7

我正在尝试为圆的一部分的外观设置动画。为了存档这个,我使用了一个安静的 CABasicAnimations。

动画从顶部开始,安静地移动到整个圆圈的三分之一。但是当动画结束时,圆圈会立即被完全绘制出来。

我怎样才能防止这种情况?

这是我的自定义 UIView 的源代码:

- (void)drawRect:(CGRect)rect
{
    int radius = 100;
    int strokeWidth = 10;
    CGColorRef color = [UIColor redColor].CGColor;
    int timeInSeconds = 5;

    CGFloat startAngle = 0;
    CGFloat endAngle = 0.33;

    CAShapeLayer *circle = [CAShapeLayer layer];

    circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius].CGPath;

    circle.position = CGPointMake(CGRectGetMidX(self.frame)-radius, CGRectGetMidY(self.frame)-radius);

    circle.fillColor = [UIColor clearColor].CGColor;
    circle.strokeColor = color;
    circle.lineWidth = strokeWidth;

    [self.layer addSublayer:circle];

    CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    drawAnimation.duration            = timeInSeconds;
    drawAnimation.repeatCount         = 1.0;
    drawAnimation.removedOnCompletion = NO;

    drawAnimation.fromValue = [NSNumber numberWithFloat:startAngle];
    drawAnimation.toValue   = [NSNumber numberWithFloat:endAngle];

    drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

    [circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"];
}
4

1 回答 1

18

当您将动画应用到图层时,Core Animation 会创建图层的副本并为副本的属性设置动画。原始层称为模型层,副本称为表示层。动画永远不会改变模型层的属性。

您尝试通过设置为来解决此removedOnCompletion问题NO。您还必须设置fillMode动画的 才能使其工作,但这并不是为属性设置动画的真正正确方法。

正确的方法是更改​​模型层的属性,然后应用动画。

// Change the model layer's property first.
circle.strokeEnd = endAngle;

// Then apply the animation.
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
drawAnimation.duration            = timeInSeconds;
drawAnimation.fromValue = [NSNumber numberWithFloat:startAngle];
drawAnimation.toValue   = [NSNumber numberWithFloat:endAngle];
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[circle addAnimation:drawAnimation forKey:@"drawCircleAnimation"];

这在 WWDC 2011 的Core Animation Essentials视频中进行了解释。我强烈推荐观看。

于 2012-02-04T18:08:36.323 回答