Color-Picker-for-iOS icon indicating copy to clipboard operation
Color-Picker-for-iOS copied to clipboard

How to get hex color value?

Open NirajCapermint opened this issue 3 years ago • 2 comments

NirajCapermint avatar Nov 18 '20 05:11 NirajCapermint

You can add an extension :

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
        }
    }
}

And then just call it:

colorPicker.color.rgb() // will return somthing like 0xDBDDE0

Que20 avatar Jul 22 '21 11:07 Que20

Thanks @Que20 will try out this.

NirajCapermint avatar Jul 22 '21 11:07 NirajCapermint