使用UIBezierPath绘制弧线的动画效果

7

我使用以下方法绘制了一条弧线:

- (void)drawRect:(CGRect)rect {
    UIBezierPath *stripePath = [UIBezierPath bezierPath];
    [arcColor set];
    [stripePath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:clockwise];
    stripePath.lineWidth = arcWidth;
    stripePath.lineCapStyle = kCGLineCapRound;
    stripePath.lineJoinStyle = kCGLineCapRound;
    [stripePath stroke];
}

现在我想通过角度来动画显示这个弧形。

我尝试使用以下代码:

angle = startAngle;
[UIView animateWithDuration:1
                      delay:0
                    options:UIViewAnimationOptionCurveEaseInOut
                 animations:^{
                     angle = endAngle;
                     [stripePath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:angle clockwise:clockwise];
                     [stripePath stroke];
}];

然而,屏幕上没有显示任何动画。如何使用角度作为变化的变量来使弧形动起来?谢谢。

2个回答

6
以下代码实现了我的目标:
UIBezierPath *stripePath = [UIBezierPath bezierPath];
[arcColor set];
stripePath.lineWidth = arcWidth;
stripePath.lineCapStyle = kCGLineCapRound;
stripePath.lineJoinStyle = kCGLineCapRound;
[stripePath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:clockwise];

[_stripeLayer setPath:stripePath.CGPath];
[_stripeLayer setStrokeColor:arcColor.CGColor];
[_stripeLayer setFillColor:[UIColor clearColor].CGColor];
[_stripeLayer setLineWidth:arcWidth];
[_stripeLayer setStrokeStart:0.0];
[_stripeLayer setStrokeEnd:1.0];
[_stripeLayer setLineCap:kCALineCapRound];
[_stripeLayer setLineJoin:kCALineCapRound];

if ([_stripeLayer superlayer]) {
    [_stripeLayer removeAllAnimations];
    [_stripeLayer removeFromSuperlayer];

}
[self.layer addSublayer:_stripeLayer];

CABasicAnimation *animateStrokEnd = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
animateStrokEnd.duration = 1;
animateStrokEnd.fromValue = [NSNumber numberWithFloat:0.0];
animateStrokEnd.toValue = [NSNumber numberWithFloat:1.0];
[_stripeLayer addAnimation:animateStrokEnd forKey:nil];

1
在这种情况下,stripeLayer是什么?它是CAShapeLayer吗? - Bishal Ghimire
这应该是被接受的答案。请注意,不需要将图层从层次结构中删除并重新添加,只需删除动画并创建一个新的即可。 - Nikolay Spassov

-3

我按照您提供的链接解决了我的问题。尽管您没有提供代码,但我仍然接受您的回答。如果有人看到了我的代码,请投票支持我,谢谢! - Wingzero
4
虽然这个回答理论上可以回答问题,但最好包含答案的主要部分并提供链接作为参考。 - Jojodmo

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