Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Convert UIColor to Hexa Color Code

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 876
    Comment on it

    Hi,

     

    If you want to get the HexaDecimal String code for any color then below code will surely help you to come out with the hexa color string.

    Here are the steps to get hexa code string for any color.

     

    1- Declare the variables for red, green, blue and alpha.

    var red:CGFloat = 0
    var green:CGFloat = 0
    var blue:CGFloat = 0
    var alpha:CGFloat = 0

     

    2- Use the method below to mutate the variable declared in #1.

    yourUIColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

    If the color is in compatible color space it will return the component in RGB which are making the color else the passed parameters won’t change.


    3- Now use bitwise left shift operator to calculate the rgb.  (Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are blue).

    let rgb:Int = (Int)(red*255)<<16 | (Int)(green*255)<<8 | (Int)(blue*255)<<0

     

    4- Convert the obtained value(from step #4) as string now.

    NSString(format:"#%06x", rgb) as String


    Code Snippet:

    func toHexString(color:UIColor) -> String {
            var red:CGFloat = 0
            var green:CGFloat = 0
            var blue:CGFloat = 0
            var alpha:CGFloat = 0
            color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
            let rgb:Int = (Int)(red*255)<<16 | (Int)(green*255)<<8 | (Int)(blue*255)<<0
            return NSString(format:"#%06x", rgb) as String
    }

     

    Thank You

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: