2015-01-03 269 views
1

我正在使用以下代码绘制圆的一部分。不过,我有点困惑,因为在动画结束时,它似乎立即填充了圈子的其余部分。这是为什么发生?动画 - 在iOS中绘制圆圈 - 未完成圆圈动画

// Set up the shape of the circle 
int radius = 62; 
CAShapeLayer *circle = [CAShapeLayer layer]; 
// Make a circular shape 
circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) 
             cornerRadius:radius].CGPath; 
// Center the shape in self.view 
circle.position = CGPointMake(18, 92); 

// Configure the apperence of the circle 
circle.fillColor = [UIColor clearColor].CGColor; 
circle.strokeColor = [UIColor whiteColor].CGColor; 
circle.lineWidth = 5; 

// Add to parent layer 
[cell.layer addSublayer:circle]; 

// Configure animation 
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"]; 
drawAnimation.duration   = .8; // "animate over 10 seconds or so.." 
drawAnimation.repeatCount   = 1.0; // Animate only once.. 

// Animate from no part of the stroke being drawn to the entire stroke being drawn 
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f]; 
drawAnimation.toValue = [NSNumber numberWithFloat:0.4f]; 

// Experiment with timing to get the appearence to look the way you want 
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; 

回答

0

对于整个行程是动画drawAnimation.fromValue应该0.0drawAnimation.toValue应该1.0。这些值确定中风的百分比是动画的。

drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f]; 
drawAnimation.toValue = [NSNumber numberWithFloat:1.0f]; 

fromValue : Defines the value the receiver uses to start interpolation. 
toValue : Defines the value the receiver uses to end interpolation. 

你使用的是什么0.4drawAnimation.toValue。所以它在动画的40%结束,并且一次性吸引其余的动画而没有动画。

例如,如果您设置drawAnimation.fromValue = 0.5drawAnimation.toValue = 1.0, 动画将从半个圆圈开始。 如果您设置了drawAnimation.fromValue = 0.0drawAnimation.toValue = 0.5, 动画将以半圈结束并在没有动画的情况下绘制其余部分。

如果您只想绘制圆的40%,您可以使用不同的函数来创建圆的路径。

CGFloat startAngle = (-M_PI/2); 
CGFloat endAngle = startAngle + 0.4*(2*M_PI); 

circle.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(radius, radius) 
                 radius:radius 
                startAngle:startAngle 
                endAngle:endAngle 
                clockwise:YES].CGPath; 

上述代码实际上从startAngle = -M_PI/2生成40%的圆形路径。你可以根据你的需要改变角度。

+0

我明白了。我如何解决这个问题,所以我只画出40%的圈子? – Apollo

+0

哦,你想绘制只有40%的圈子?而不是其余? – rakeshbs

1

发生这种情况的原因是默认情况下,完成后会从图层中移除。这意味着它将删除您动画的值,并在动画完成后立即将其设置为默认值1.0。由于您使用的是CAAnimation,图层实际上从来没有真正改变它的属性,它只是看起来像是这是为什么当动画被移除时,它被设置为1.0,因为这是strokeEnd的图层值,因为您从未改变它。尝试通过在动画发生时打印strokeEnd的值来自己查看。

这可以通过2种方法解决,在开始动画之前设置最终的storkeEnd值,以便当它被移除时仍然是0.4或向CABasicAnimation添加某些属性。你需要设置以达到你想要的属性是:

drawAnimation.fillMode = kCAFillModeForwards

drawAnimation.removedOnCompletion = false

希望帮助