Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Draw a Circle around a Label

I'm trying to draw a circle around a label at runtime in a TableViewCell's cell.

I can figure out how to get it roughly around the label, but I'm having some trouble centring it exactly around the label.

The circle seems to be drawing just to the right and towards the middle of the label.

Here's my code so far, I'm sure this will be easy for someone to bang out.

func drawCircle() {
    let x = countLabel.layer.position.x - (countLabel.frame.width)
    let y = countLabel.layer.position.y - (countLabel.frame.height / 2)
    let circlePath = UIBezierPath(roundedRect: CGRectMake(x, y, countLabel.frame.height, countLabel.frame.height), cornerRadius: countLabel.frame.height / 2).CGPath

    let circleShape = CAShapeLayer()
    circleShape.path = circlePath
    circleShape.lineWidth = 3
    circleShape.strokeColor = UIColor.whiteColor().CGColor
    circleShape.fillColor = UIColor.clearColor().CGColor

    self.layer.addSublayer(circleShape)
}
like image 393
Kristofer Doman Avatar asked Sep 22 '15 16:09

Kristofer Doman


2 Answers

You can instead just use corner radius on your label's layer. You make the label square and then set its layer's corner radius to half the width/height of the label which will make it perfectly round. The you set the border width to something greater than zero and the border color to the stroke color you want to use.

let size:CGFloat = 35.0 // 35.0 chosen arbitrarily

countLabel.bounds = CGRectMake(0.0, 0.0, size, size) 
countLabel.layer.cornerRadius = size / 2
countLabel.layer.borderWidth = 3.0
countLabel.layer.backgroundColor = UIColor.clearColor().CGColor
countLabel.layer.borderColor = UIColor.greenColor().CGColor

It will look something like this:

enter image description here

Although the full code for that goes like this in a single view controller iPad template project:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let size:CGFloat = 35.0 // 35.0 chosen arbitrarily

        let countLabel = UILabel()
        countLabel.text = "5"
        countLabel.textColor = .greenColor()
        countLabel.textAlignment = .Center
        countLabel.font = UIFont.systemFontOfSize(14.0)
        countLabel.bounds = CGRectMake(0.0, 0.0, size, size)
        countLabel.layer.cornerRadius = size / 2
        countLabel.layer.borderWidth = 3.0
        countLabel.layer.backgroundColor = UIColor.clearColor().CGColor
        countLabel.layer.borderColor = UIColor.greenColor().CGColor

        countLabel.center = CGPointMake(200.0, 200.0)

        self.view.addSubview(countLabel)
    }

}
like image 103
Matt Long Avatar answered Nov 09 '22 09:11

Matt Long


countLabel.layer.cornerRadius = 0.5 * countLabel.bounds.size.width 
like image 2
Lengo Avatar answered Nov 09 '22 08:11

Lengo