将CAShapeLayer设置为动画,绘制进度圆形。

12

我正在尝试绘制一个圆来指示进度。进度更新可能会很快,我希望能够对圆的变化进行动画处理。

我已经尝试使用以下方法,但似乎没有任何效果。这种操作是否可行?

- (id)initWithFrame:(CGRect)frame strokeWidth:(CGFloat)strokeWidth insets:(UIEdgeInsets)insets
{
    if (self = [super initWithFrame:frame])
    {

        self.strokeWidth = strokeWidth;

        CGPoint arcCenter = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
        CGFloat radius = CGRectGetMidX(self.bounds) - insets.top - insets.bottom;

        self.circlePath = [UIBezierPath bezierPathWithArcCenter:arcCenter
                                                         radius:radius
                                                     startAngle:M_PI
                                                       endAngle:-M_PI
                                                      clockwise:YES];
        [self addLayer];
    }
    return self;
}


- (void)setProgress:(double)progress {
    _progress = progress;
    [self updateAnimations];
}

- (void)addLayer {

    CAShapeLayer *progressLayer = [CAShapeLayer layer];
    progressLayer.path = self.circlePath.CGPath;
    progressLayer.strokeColor = [[UIColor whiteColor] CGColor];
    progressLayer.fillColor = [[UIColor clearColor] CGColor];
    progressLayer.lineWidth = self.strokeWidth;
    progressLayer.strokeStart = 10.0f;
    progressLayer.strokeEnd = 40.0f;

    [self.layer addSublayer:progressLayer];
    self.currentProgressLayer = progressLayer;

}

- (void)updateAnimations{

    self.currentProgressLayer.strokeEnd = self.progress;
    [self.currentProgressLayer didChangeValueForKey:@"endValue"];
}

目前这段代码甚至无法画圆,但是删除 progressLayer 的 strokeStartstrokeEnd 将绘制完整的圆。

我该如何使其从某一点开始,并根据我的进度设置开始绘制圆形?


7
我不想使用第三方代码。我想要理解如何自己完成它。 - Nic Hubbard
1
"我不想使用第三方代码。我想要理解如何自己做。" +1。我感同身受。 - Unheilig
2个回答

6
我想通了。 strokeStartstrokeEnd 的值在0.0到1.0之间,所以我给它的值太高了。
因此,我只是更新了我的设置为:
- (void)setProgress:(double)progress {
    _progress = progress * 0.00460;
    [self updateAnimations];
}

1

我的回答,带有示例这里。一般来说,您应该将动画添加到CAShapeLayer


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接