[英]Animation - Drawing a circle in iOS - Not animating complete circle
我正在使用以下代码绘制圆的一部分。 但是,我有点困惑,因为在动画结束时,它似乎立即填充了圆圈的其余部分。 为什么会这样呢?
// 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];
发生这种情况是因为默认情况下,完成时会从图层中删除CAAnimation
。 这意味着它将在动画结束后立即删除您设置动画的值,并将其设置为默认值1.0
。 由于您使用的是CAAnimation
该图层实际上从未更改其属性,而只是看起来是这样,这就是为什么在删除动画时将其设置为1.0
原因,这就是该图层的strokeEnd
值,因为您从未更改过。 尝试通过在动画发生时打印strokeEnd
的值来自己查看。
这可以通过两种方式解决:在启动动画之前设置最终的storkeEnd
值,以使其在删除时仍为0.4
或者通过向CABasicAnimation
添加某些属性来解决。 您需要设置以实现所需内容的属性是:
drawAnimation.fillMode = kCAFillModeForwards
和
drawAnimation.removedOnCompletion = false
希望能有所帮助
对于要进行动画drawAnimation.fromValue
的整个笔画, drawAnimation.fromValue
应该为0.0
而drawAnimation.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.4
作为drawAnimation.toValue
。 因此,它在动画的40%
处结束,并在不设置动画的情况下一次性绘制其余部分。
例如,如果您设置drawAnimation.fromValue = 0.5
和drawAnimation.toValue = 1.0
,则动画将从半个圆圈开始。 如果将drawAnimation.fromValue = 0.0
设置drawAnimation.fromValue = 0.0
drawAnimation.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%的圆形路径。 您可以根据需要改变角度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.