Swift: Draw a Circle around a Label Swift: Draw a Circle around a Label swift swift

Swift: Draw a Circle around a Label


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 arbitrarilycountLabel.bounds = CGRectMake(0.0, 0.0, size, size) countLabel.layer.cornerRadius = size / 2countLabel.layer.borderWidth = 3.0countLabel.layer.backgroundColor = UIColor.clearColor().CGColorcountLabel.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 UIKitclass 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)    }}


countLabel.layer.cornerRadius = 0.5 * countLabel.bounds.size.width 


Ugh, it was what I thought, silly mistake.

X and Y are calculated from the middle instead of from the top left when dealing with BezierPath's.

So the code for x and y should be as follows:

let x = countLabel.layer.position.x - (countLabel.frame.height / 2)let y = countLabel.layer.position.y - (countLabel.frame.height / 2)