圆段笔划的动画以完整笔划结束

Shi*_*goo 7 cocoa-touch core-animation objective-c cabasicanimation ios

我试图动画一段圆的外观.为了存档这个我使用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"];
}
Run Code Online (Sandbox Code Playgroud)

rob*_*off 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"];
Run Code Online (Sandbox Code Playgroud)

这是在解释核心动画精华视频2011 WWDC.我强烈推荐观看它.