Search code examples
swiftcolorsuicoloruint

How to convert value of type UIColor to Uint in swift


I got this UIColor :

UIColor(red: 0.2, green: 0.4118, blue: 0.1176, alpha: 1.0) 

And I need to convert in Uint. How can I do that?

EDIT :

func showEmailMessage(advice : String)
{
    _ = SCLAlertView().showSuccess("Congratulation", subTitle: advice, closeButtonTitle: "Ok", duration : 10, colorStyle: 0x33691e, colorTextButton: 0xFFFFFF)
}

Color style field want Uint


Solution

  • You can make use of the UIColor.getRed(...) method to extract the colors as CGFloat, thereafter convert the values of your CGFloat triplet to the proper bit positions of an UInt32 variable.

    // Example: use color triplet CC6699 "=" {204, 102, 153} (RGB triplet)
    let color = UIColor(red: 204.0/255.0, green: 102.0/255.0, blue: 153.0/255.0, alpha: 1.0)
    
    // read colors to CGFloats and convert and position to proper bit positions in UInt32
    var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
    if color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
    
        var colorAsUInt : UInt32 = 0
    
        colorAsUInt += UInt32(red * 255.0) << 16 + 
                       UInt32(green * 255.0) << 8 + 
                       UInt32(blue * 255.0)
    
        colorAsUInt == 0xCC6699 // true
    }
    

    For details, see e.g. the Language Guide - Advanced Operators which contains, among other valuable things, an example specifically for bit shifting w.r.t RGB triplets.