Kristofer Doman Kristofer Doman - 2 months ago 3
Swift Question

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



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)