How do I get the RGB values of a UIColor?

47 views Asked by At

I ran into a problem with converting UIColors to CGColors and CIColors which I couldn't figure out for an embarrassing amount of time. This post I'm just answering my own question here. I found a handful of solutions, but some of them would end up throwing unnecessary exceptions.

This is my top choice of solutions:

extension UIColor {

func getRed() -> Int {
    return Int(self.cgColor.components![0]*255)
}

func getGreen() -> Int {
    return Int(self.cgColor.components![1]*255)
}

func getBlue() -> Int {
    return Int(self.cgColor.components![2]*255)
}

func getAlpha() -> Int {
    return Int(self.cgColor.components![3]*255)
}

func getRGB() -> [Int] {
    return [Int(self.cgColor.components![0]*255),
            Int(self.cgColor.components![1]*255),
            Int(self.cgColor.components![2]*255),
            Int(self.cgColor.components![3]*255)]
    }
}

Usage:

let color = UIColor.white
let r = color.getRed()
let g = color.getGreen()
let b = color.getBlue()
let a = color.getAlpha()
let rgba = color.getRed()

If you find a better solution, please add it. This post is just to help people like me who had a difficult time finding a solution to their problem.

0

There are 0 answers