首页 > 解决方案 > CABasicAnimation 从当前位置反转(如进度条动画)

问题描述

我在我的应用程序中使用一个圆圈(UIBezierPath)作为迷你进度条。我遇到的一个问题是我只能在一个方向上为圆设置一次动画。假设我将圆圈绘制到 80%,我想将其缩小到 60%,整个圆圈被重新绘制,这不是我想要的。

使用进度条时,如果减少当前显示的百分比,则不会重绘整个进度条,进度条只会从当前位置缩小到新百分比,这就是我想要的圆形图层。

这是我的圈子初始设置代码:

CAShapeLayer *greenPlayButtonCircle;

greenPlayButtonCircle = [CAShapeLayer layer];
[greenPlayButtonCircle setPath:[UIBezierPath bezierPathWithArcCenter:CGPointMake(boxView.bounds.origin.x, boxView.bounds.origin.y) radius:(boxView.frame.size.width / 2) startAngle:DEGREES_TO_RADIANS(-90) endAngle:DEGREES_TO_RADIANS(270) clockwise:YES].CGPath];
[greenPlayButtonCircle setFillColor:[UIColor clearColor].CGColor];
[greenPlayButtonCircle setStrokeColor:[UIColor greenColor].CGColor];
[greenPlayButtonCircle setLineWidth:6.0];
[greenPlayButtonCircle setPosition:boxView.center];
[greenPlayButtonCircle setAnchorPoint:CGPointMake(0.5, 0.5)];
    
[self.view.layer addSublayer:greenPlayButtonCircle];

这是我用来尝试减少圆圈百分比的代码(绘制部分):

[greenPlayButtonCircle setPath:[UIBezierPath bezierPathWithArcCenter:CGPointMake(boxView.bounds.origin.x, boxView.bounds.origin.y) radius:(boxView.frame.size.width / 2) startAngle:DEGREES_TO_RADIANS(-90) endAngle:DEGREES_TO_RADIANS(270) clockwise:YES].CGPath];
    
// Setup the circle animation.
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
[animation setDuration:0.5];
[animation setRemovedOnCompletion:YES];
[animation setFromValue:@(0)];
[animation setToValue:@(1)];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
[animation setFillMode:kCAFillModeBoth];
    
// Begin the circle animation.
[greenPlayButtonCircle addAnimation:animation forKey:@"drawCircleAnimation"];

这是圆圈最初的样子(设置为 100% - 这是我想要的):

在此处输入图像描述

现在我想减少圆圈百分比或大小,这就是我希望它动画的方式:

在此处输入图像描述

这就是实际发生的事情(整个圆圈被重新绘制,这不是我想要的):

在此处输入图像描述

有没有办法执行反向动画?

标签: iosobjective-cuibezierpathcashapelayercabasicanimation

解决方案


您可以使用fromValuetoValue属性来控制它,例如将圆形路径从 100% 减少到 80%:

[animation setFromValue:@(1)];
[animation setToValue:@(0.8)];

推荐阅读