Useful CGFloat Extensions

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.

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):

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