带有CAShapeLayer和CABasicAnimation的循环进度条

时间:2018-05-15 15:03:22

标签: ios objective-c progress-bar

我正在尝试使用here

中的想法制作循环进度视图

这是我的CircleView代码:

#import "CircleView.h"

@interface CircleView()

@property (nonatomic, strong) CAShapeLayer *circleLayer;

@end

@implementation CircleView

-(instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];

if (self) {
    self.backgroundColor = UIColor.clearColor;

    UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width / 2., self.frame.size.height / 2.0) radius: (self.frame.size.width - 10) / 2 startAngle:0.0 endAngle:M_PI * 2 clockwise:YES];

    CAShapeLayer *downLayer = [[CAShapeLayer alloc] init];
    downLayer.path = circlePath.CGPath;
    downLayer.fillColor = UIColor.clearColor.CGColor;
    downLayer.strokeColor = UIColor.lightGrayColor.CGColor;
    downLayer.lineWidth = 10.0;

    downLayer.strokeEnd = 1.0;

    self.circleLayer = [[CAShapeLayer alloc] init];
    self.circleLayer.path = circlePath.CGPath;
    self.circleLayer.fillColor = UIColor.clearColor.CGColor;
    self.circleLayer.strokeColor = UIColor.redColor.CGColor;
    self.circleLayer.lineWidth = 10.0;

    self.circleLayer.strokeEnd = 0.0;

    [self.layer addSublayer:downLayer];
    [self.layer addSublayer: self.circleLayer];
}

return self;
}

-(void)animateCircle:(NSTimeInterval)duration fromPart:(CGFloat)fromPart toPart: (CGFloat)toPart {

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];

animation.duration = duration;

animation.fromValue = @(fromPart);
animation.toValue = @(toPart);

animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

self.circleLayer.strokeEnd = toPart;

[self.circleLayer addAnimation:animation forKey:@"animateCircle"];

}

@end

问题是当我尝试不止一次制作这个动画时。然后它只显示上次调用的动画,就像之前的调用已完成动画一样。例如,如果我进行以下两次调用:

[self.circleView animateCircle:1 fromPart:0.0 toPart:0.25];
[self.circleView animateCircle:1 fromPart:0.25 toPart:0.5];

仅显示从0.25%的圆圈到圆圈的0.5%的颜色的动画。我可以改变吗?我需要一个接一个地显示所有动画。 (需要显示下载的进度)

1 个答案:

答案 0 :(得分:1)

您需要删除这两行以下内容并按预期方式工作。

animation.fromValue = @(fromPart);
animation.toValue = @(toPart);

因为您使用CircleView来显示下载进度,所以在制作动画圆圈时,您的方法不需要fromPart值。您可以像下面的代码一样更新animateCircle方法。

-(void)animateCircle:(NSTimeInterval)duration toPart: (CGFloat)toPart {

  CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];

  animation.duration = duration;

  animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];

  self.circleLayer.strokeEnd = toPart;

  [self.circleLayer addAnimation:animation forKey:@"animateCircle"];

}

结果

enter link description here