Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HEX value in Objective-C

I want to create UIColor from HEX value. But my Color is a NSString. So i implement this solution: How can I create a UIColor from a hex string?

code:

#define UIColorFromRGB(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

And then i have (simplify):

NSString *myString = [[NSString alloc] initWithString:@"0xFFFFFF"];

So when i want to call macro:

UIColor *myColor = UIColorFromRGB(myString);

I'm getting an error: invalid operands to binary expression ('NSString *' and 'int')

So i know i have to pass int, but how to convert NSString to int in this case? Of course [myString intValue]; does not work here.

like image 414
Jakub Avatar asked Apr 24 '12 11:04

Jakub


People also ask

How do you convert Heicolor to hex?

To convert a UIColor instance to a hex value, we define a convenience method, toHex(alpha:) . The method accepts one parameter of type Bool , which indicates whether the alpha value should be included in the string that is returned from the method.


1 Answers

You can either use your macro directly with hex integers like this:

UIColorFromRGB(0xff4433)

Or you can parse the hex-string into an integer like this:

unsigned colorInt = 0;
[[NSScanner scannerWithString:hexString] scanHexInt:&colorInt];
UIColorFromRGB(colorInt)
like image 155
Heiberg Avatar answered Oct 17 '22 17:10

Heiberg