Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 549
xushunwang Avatar asked Dec 27 '12 08:12

xushunwang


People also ask

How do I get hex code from UIColor Swift?

there is a method called hexFromUIColor: all you need to do is call it like NSString *hexStr = [UIColor hexFromUIColor:[UIColor redColor]]; Just take the code that you need.

How do you convert RGBA to hex?

Converting RGBA to hex with the #rgba or #rrggbbaa notation follows virtually the same process as the opaque counterpart. Since the alpha ( a ) is normally a value between 0 and 1, we need to multiply it by 255, round the result, then convert it to hexadecimal.

Is it better to use RGB or hex?

HEX, or hexadecimal numbers, is a human-friendly way to communicate color to computers. There is no informational difference between RGB and HEX colors; they are simply different ways of communicating the same thing – a red, green, and blue color value.


1 Answers

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; } 
like image 57
Anoop Vaidya Avatar answered Oct 21 '22 00:10

Anoop Vaidya