richc
richc

Reputation: 1678

How to add corner radius to a UIBezier Path Arc

I am creating an arc using UIBezierPath arc convenience method. I want the ends of the arc to be rounded off - see attached sketch for exact requirement! The cornerRadius option used in the roundedRect version isn't available for the arc method. Anyone got an ideas on how to achieve this? Thanks in advance. (This is different to previously asked question in that it provides exact requirement)

 let center = CGPoint(x:bounds.width/2, y: bounds.height/2)
 let radius: CGFloat = max(bounds.width, bounds.height)
 let arcWidth: CGFloat = 10
 let startAngle: CGFloat = 4.6 / 3 * π
 let endAngle: CGFloat = 4.4 / 3 * π

 let path = UIBezierPath(arcCenter: center, radius: radius/2 - arcWidth/2, startAngle: startAngle, endAngle: endAngle, clockwise: true)

 path.lineWidth = arcWidth
 // all thats needed to make the ends rounded is
 path.lineCapStyle = .Round
 path.stroke()

enter image description here

Upvotes: 5

Views: 2875

Answers (2)

richc
richc

Reputation: 1678

All thats needed is to add one line of code: path.lineCapStyle = .Round.

Upvotes: 7

E-Riddie
E-Riddie

Reputation: 14780

Solution

What actually does the trick is lineCap property. You can use the code below.

func drawCircle(view: UIView, startingAngle: CGFloat, endAngle: CGFloat) -> CAShapeLayer {
    let path = UIBezierPath(arcCenter: view.center, radius: CGFloat((view.bounds.size.height/2) - 10), startAngle: startingAngle, endAngle:endAngle, clockwise: true)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.CGPath

    shapeLayer.strokeColor = UIColor.blackColor().CGColor
    shapeLayer.lineWidth = 10.0
    shapeLayer.fillColor = UIColor.clearColor().CGColor
    shapeLayer.lineCap = kCALineCapRound

    view.layer.addSublayer(shapeLayer)

    return shapeLayer
}

Result

enter image description here

Upvotes: 16

Related Questions