How can I get a hex string from UIColor or from rgb

Use this method :

- (NSString *)hexStringForColor:(UIColor *)color {
      const CGFloat *components = CGColorGetComponents(color.CGColor);
      CGFloat r = components[0];
      CGFloat g = components[1];
      CGFloat b = components[2];
      NSString *hexString=[NSString stringWithFormat:@"%02X%02X%02X", (int)(r * 255), (int)(g * 255), (int)(b * 255)];
      return hexString;
}

Anoop answer is not correct as if you try it with [UIColor blackColor] it will return green color's hex string.
Reason is system is cleaver enough to save memory it will set

For black color
component[0] = 0 (r=0,g=0,b=0) and
component[1] = 1 (a=1).

For white color
component[0] = 1 (r=1,g=1,b=1) and
component[1] = 1 (a=1).


Use below category for UIColor to hex
UIColor+Utility.h
@interface UIColor (Utility)

/**
 Return representaiton in hex
 */
-(NSString*)representInHex;
@end

UIColor+Utility.m

@implementation UIColor (Utility)
-(NSString*)representInHex
{
    const CGFloat *components = CGColorGetComponents(self.CGColor);
    size_t count = CGColorGetNumberOfComponents(self.CGColor);

    if(count == 2){
        return [NSString stringWithFormat:@"#%02lX%02lX%02lX",
                lroundf(components[0] * 255.0),
                lroundf(components[0] * 255.0),
                lroundf(components[0] * 255.0)];
    }else{
        return [NSString stringWithFormat:@"#%02lX%02lX%02lX",
                lroundf(components[0] * 255.0),
                lroundf(components[1] * 255.0),
                lroundf(components[2] * 255.0)];
    }
}
@end


This is the code that I used in Swift, please be aware that this seems to work fine when you send it a UIColor created with the rgba values, but returns some strange results when sending pre-defined colours like UIColor.darkGrayColor()

func hexFromUIColor(color: UIColor) -> String 
{
let hexString = String(format: "%02X%02X%02X", 
Int(CGColorGetComponents(color.CGColor)[0] * 255.0),
Int(CGColorGetComponents(color.CGColor)[1] *255.0),
Int(CGColorGetComponents(color.CGColor)[2] * 255.0))
return hexString
}

Use this Extension of UIColor to get hexString from it.

  extension UIColor {
        func toHexString() -> String {
            var r:CGFloat = 0
            var g:CGFloat = 0
            var b:CGFloat = 0
            var a:CGFloat = 0

            getRed(&r, green: &g, blue: &b, alpha: &a)

            let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0

            return String(format:"#%06x", rgb)
        }
    }

Tags:

Objective C