【问题标题】:Apply rounded corners to arc created with UIBezierPath将圆角应用于使用 UIBezierPath 创建的弧
【发布时间】:2023-10-30 14:47:02
【问题描述】:

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

我的问题是:如何让圆弧的边缘变成圆形而不是矩形?

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

 // 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,但它似乎什么也没返回。

任何帮助将不胜感激。

提前谢谢你!

花岗岩

【问题讨论】:

    标签: objective-c uibezierpath


    【解决方案1】:

    lineCapStyle 设置为kCGLineCapRound(在贝塞尔路径上)以绘制圆边线的末端。

    你也可以在形状层上设置lineCap来做同样的事情。

    【讨论】:

    • @Grangji 在您的示例中,它仍然无法正常工作。我做错了什么?
    • 应该在 CAShapeLayer 上设置,而不是在 UIBezierPath 上。
    【解决方案2】:

    你可以用这个来做圆角。

    arc.lineCap = @"round";
    

    【讨论】:

    • 使用适当的等价常量! kCGLineCapRound
    • @Warpling 我尝试使用 kCGLineCapRound 但没有成功。用“圆”它工作。知道为什么 kCGLineCapRound 不起作用吗?
    • @RajTandel 我不确定。您确定要设置lineCap 而不是lineCapStyle
    • 使用这个:layer.lineCap = kCALineCapRound; document
    【解决方案3】:

    swift 等价物是:

    let circlePath = UIBezierPath(…)
    circlePath.lineCapStyle = .round
    

    【讨论】:

    • 如果问题中有标签swift 或任何相关内容?
    最近更新 更多