0

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.

  • If you have no questions, what's the point of your opening a new topic? If you want to show off your wisdom, don't you think you should do it on your blog or something? – El Tomato Dec 18 '16 at 04:14
  • 1
    @ElTomato - There's nothing wrong with him doing this (if he had 15 reputation), though it would have been better to post as question and then post the answer separately to preserve the Q&A structure of Stack Overflow. But see [Can I answer my own question?](http://stackoverflow.com/help/self-answer) This practice is encouraged when someone discovers something that might be useful for others. – Rob Dec 18 '16 at 04:16
  • Admittedly, this has been asked and answered before, though, so this should be closed as a duplicate of http://stackoverflow.com/questions/28532564/extract-rgb-values-from-uicolor or http://stackoverflow.com/questions/437113/how-to-get-rgb-values-from-uicolor. – Rob Dec 18 '16 at 04:20
  • @Rob I see. My apology... Thanks, Rob. And, yes, there have been some answers to the same question. – El Tomato Dec 18 '16 at 04:23

0 Answers0