Kashif Kashif - 3 months ago 66
Swift Question

iOS: Draw circle as percentage in UIView

I have one

UIView
in circular shape, I need to show that
UIView
border colour in percentage value like if percentage value is 50%, it should fill half border colour of UIView. I have used
UIBeizer
path
addArcWithCenter
however I didn't get perfect solution. Please help me in this

Answer

You can achieve it with following code, simply adjust strokeStart and strokeEnd:

    // round view
    let roundView = UIView(frame: CGRectMake(100, 100, 250, 250))
    roundView.backgroundColor = UIColor.whiteColor()
    roundView.layer.cornerRadius = roundView.frame.size.width / 2

    // bezier path
    let circlePath = UIBezierPath(arcCenter: CGPoint (x: roundView.frame.size.width / 2, y: roundView.frame.size.height / 2),
                                  radius: roundView.frame.size.width / 2,
                                  startAngle: CGFloat(-0.5 * M_PI),
                                  endAngle: CGFloat(1.5 * M_PI),
                                  clockwise: true)
    // circle shape
    let circleShape = CAShapeLayer()
    circleShape.path = circlePath.CGPath
    circleShape.strokeColor = UIColor.redColor().CGColor
    circleShape.fillColor = UIColor.clearColor().CGColor
    circleShape.lineWidth = 1.5
    // set start and end values
    circleShape.strokeStart = 0.0
    circleShape.strokeEnd = 0.8

    // add sublayer
    roundView.layer.addSublayer(circleShape)
    // add subview
    self.view.addSubview(roundView)
Comments