I’ve been working a lot with `CALayers`

over the past few days, specifically layers with circular shapes, and so these two little extensions have been really useful.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
extension CGFloat { func degreesToRads() -> CGFloat { let rads = self * CGFloat(M_PI / 180 ) return rads } func positionOnCircleInRect(rect : CGRect) -> CGPoint { let rads = self.degreesToRads() - CGFloat( M_PI / 2) // Assume square let x = rect.size.width / 2 * CGFloat(cos(rads)) let y = rect.size.height / 2 * CGFloat(sin(rads)) return CGPointMake(x + (rect.size.height / 2) + rect.origin.x, y + (rect.size.height / 2) + rect.origin.x) } } |

The first is your standard degrees to radians conversion function that every programmer that’s worked with UI has probably written at some point.

The second is a bit more interesting, though, as it finds a point on a circle within a frame of a given size (it also assumes that 0 is the top of the circle, not the right edge as in Core Animation):

1 2 3 4 |
let rectForCircle = CGRect(x: 0, y: 0, width: 50, height: 50 ) let point = CGFloat(90).positionOnCircleInRect(rectForCircle) // Returns x 50, y 25—or the point at 90º on a circle |

If you you enjoyed this, sign up to my mailing list to get my latest posts direct to your inbox.

Your email won't be shared and you can unsubscribe any time (the link’s at the bottom of every email).