使用UIBezierPath为弧线添加圆角

9

我正在制作一个使用UIBezierPath创建的圆形进度条。 进度条如下图所示:

enter image description here

我的问题是:如何使弧线的边缘变为圆形而不是矩形?

我用来绘制弧线的代码如下:

 // Draw the arc with bezier path
        int radius = 100;

        arc = [CAShapeLayer layer];
        arc.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 50) radius:radius startAngle:M_PI endAngle:M_PI/150 clockwise:YES].CGPath;
        arc.position = CGPointMake(CGRectGetMidX(self.view.frame)-radius,
                                    CGRectGetMidY(self.view.frame)-radius);
        arc.fillColor = [UIColor clearColor].CGColor;
        arc.strokeColor = [UIColor purpleColor].CGColor;
        arc.cornerRadius = 0.5;
        arc.lineWidth = 6;

        [self.view.layer addSublayer:arc];

        // Animation of the progress bar
        drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        drawAnimation.duration            = 5.0; // "animate over 10 seconds or so.."
        drawAnimation.repeatCount         = 1.0;  // Animate only once..
        drawAnimation.removedOnCompletion = YES;   // Remain stroked after the animation..
        drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
        drawAnimation.toValue   = [NSNumber numberWithFloat:10.0f];
        drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
        [arc addAnimation:drawAnimation forKey:@"drawCircleAnimation"];

我尝试使用 arc.cornerRadius,但好像没有返回任何东西。
感谢您的帮助。
提前致谢!
Granit
3个回答

20

将贝塞尔路径的lineCapStyle设置为kCGLineCapRound,可以绘制带有圆形边缘的线段端点。

您也可以在形状图层上设置lineCap来实现相同的效果。


@Grangji 在你的例子中,它仍然无法工作。我做错了什么? - Petr Brazdil
5
应该设置在 CAShapeLayer 上,而不是 UIBezierPath 上。 - Petr Brazdil

8
要使角落变得更加圆润,您可以使用以下方法。
arc.lineCap = @"round";

使用适当的常量等效值!kCGLineCapRound - Warpling
@Warpling 我尝试使用kCGLineCapRound,但它没有起作用。使用"round"却可以。你有什么想法为什么kCGLineCapRound不起作用吗? - Raj Tandel
@RajTandel 我不确定。你确定要设置 lineCap 而不是 lineCapStyle 吗? - Warpling
使用以下代码:layer.lineCap = kCALineCapRound; 文档 - J.Ren

2
快速的等价物是:
let circlePath = UIBezierPath(…)
circlePath.lineCapStyle = .round

如果问题中有标签“swift”或者任何相关的内容? - Sinto

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