xushunwang xushunwang - 1 month ago 17
Objective-C Question

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

Now I can convert a hex string to rgb color like this:

// Input is without the # ie : white = FFFFFF
+ (UIColor *)colorWithHexString:(NSString *)hexString
{
unsigned int hex;
[[NSScanner scannerWithString:hexString] scanHexInt:&hex];
int r = (hex >> 16) & 0xFF;
int g = (hex >> 8) & 0xFF;
int b = (hex) & 0xFF;

return [UIColor colorWithRed:r / 255.0f
green:g / 255.0f
blue:b / 255.0f
alpha:1.0f];
}


bu how can I convert rgb to hex string?

Answer

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