How to get the RGB Code (INT) from an UIColor in Swift

SwiftRgbUicolor

Swift Problem Overview


I would like to get the RGB Value of an UIColor in Swift:

let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)
println("RGB Value is:");
println(swiftColor.getRGB()); <<<<<< How to do that ?

In Java I would do it as follows:

Color cnew = new Color();
int iColor = cnew.rgb(1, 165/255, 0);
System.out.println(iColor);

How should I get this value?

Swift Solutions


Solution 1 - Swift

The Java getRGB() returns an integer representing the color in the default sRGB color space (bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are blue).

UIColor does not have such a method, but you can define your own:

extension UIColor {
    
    func rgb() -> Int? {
        var fRed : CGFloat = 0
        var fGreen : CGFloat = 0
        var fBlue : CGFloat = 0
        var fAlpha: CGFloat = 0
        if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
            let iRed = Int(fRed * 255.0)
            let iGreen = Int(fGreen * 255.0)
            let iBlue = Int(fBlue * 255.0)
            let iAlpha = Int(fAlpha * 255.0)
            
            //  (Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are blue).
            let rgb = (iAlpha << 24) + (iRed << 16) + (iGreen << 8) + iBlue
            return rgb
        } else {
            // Could not extract RGBA components:
            return nil
        }
    }
}

Usage:

let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)
if let rgb = swiftColor.rgb() {
    print(rgb)
} else {
    print("conversion failed")
}

Note that this will only work if the UIColor has been defined in an "RGB-compatible" colorspace (such as RGB, HSB or GrayScale). It may fail if the color has been created from an CIColor or a pattern image, in that case nil is returned.

Remark: As @vonox7 noticed, the returned value can be negative on 32-bit platforms (which is also the case with the Java getRGB() method). If that is not wanted, replace Int by UInt or Int64.

The reverse conversion is

extension UIColor {
    convenience init(rgb: Int) {
        let iBlue = rgb & 0xFF
        let iGreen =  (rgb >> 8) & 0xFF
        let iRed =  (rgb >> 16) & 0xFF
        let iAlpha =  (rgb >> 24) & 0xFF
        self.init(red: CGFloat(iRed)/255, green: CGFloat(iGreen)/255,
                  blue: CGFloat(iBlue)/255, alpha: CGFloat(iAlpha)/255)
    }
}

Solution 2 - Swift

From Martin R's answer :The method could also return a named tuple (a Swift 2 feature):

extension UIColor {

    func rgb() -> (red:Int, green:Int, blue:Int, alpha:Int)? {
        var fRed : CGFloat = 0
        var fGreen : CGFloat = 0
        var fBlue : CGFloat = 0
        var fAlpha: CGFloat = 0
        if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
            let iRed = Int(fRed * 255.0)
            let iGreen = Int(fGreen * 255.0)
            let iBlue = Int(fBlue * 255.0)
            let iAlpha = Int(fAlpha * 255.0)

            return (red:iRed, green:iGreen, blue:iBlue, alpha:iAlpha)
        } else {
            // Could not extract RGBA components:
            return nil
        }
    }
}

Solution 3 - Swift

Swift 3.0 IOS 10

let colour = UIColor.red
let rgbColour = colour.cgColor
let rgbColours = rgbColour.components

Solution 4 - Swift

Wrote an extension you can use. I chose to return the values as CGFloats rather than Ints because CGFloat is what the init method of UIColor takes

extension UIColor {
    var colorComponents: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)? {
        guard let components = self.cgColor.components else { return nil }
        
        return (
            red: components[0],
            green: components[1],
            blue: components[2],
            alpha: components[3]
        )
    }
}

Note: Swift 3.1/iOS 10 compatible, may not work in iOS 9 as UIColor.cgColor.components may be not be available

Solution 5 - Swift

Swift 4. Getting hex code (UInt) from UIColor:

extension UIColor {
    var coreImageColor: CIColor {
        return CIColor(color: self)
    }
    var hex: UInt {
        let red = UInt(coreImageColor.red * 255 + 0.5)
        let green = UInt(coreImageColor.green * 255 + 0.5)
        let blue = UInt(coreImageColor.blue * 255 + 0.5)
        return (red << 16) | (green << 8) | blue
    }
}

Solution 6 - Swift

In swift you can use Color Literal, to get RGB Color.

enter image description here

Just like that

enter image description here

I hope this will be useful to someone.

Solution 7 - Swift

Looks like its gotten simpler in recent versions, values are 0-1 so they need to be * 255 for a standard rbga result (except a)

let red = yourColor.lottieColorValue.r * 255
let blue= yourColor.lottieColorValue.b * 255
let green= yourColor.lottieColorValue.g * 255
let alpha = yourColor.lottieColorValue.a

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmcfly softView Question on Stackoverflow
Solution 1 - SwiftMartin RView Answer on Stackoverflow
Solution 2 - SwiftMatthieu RieglerView Answer on Stackoverflow
Solution 3 - Swiftuser3069232View Answer on Stackoverflow
Solution 4 - SwiftZack ShapiroView Answer on Stackoverflow
Solution 5 - SwiftbirdyView Answer on Stackoverflow
Solution 6 - SwiftBooharinView Answer on Stackoverflow
Solution 7 - SwiftedencorbinView Answer on Stackoverflow