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

回答

18

当你申请一个动画层,核心动画创建层的副本,并在动画副本的属性。原始层称为模型层,副本称为表示层。动画不会更改模型图层的属性。

您试图通过将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"]; 

这在Core Animation Essentials videoWWDC 2011解释。我强烈推荐观看它。

+0

有关'drawAnimation.duration'期间进度%(0到1)的任何想法? – Jack 2018-01-03 07:36:57