Tuesday, December 25, 2012

UIColor macro with hex values

Cocoa has several colors built into the UIColor class. For example:

?
1
2
[UIColor redColor];
[UIColor darkGrayColor];

This is great, but what if you want one of the thousands of colors not found in the pre-defined list? There's an easy way to do that:
?
1
[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];

Perfect. But what if you just have a list of hex color codes? Wouldn't it be nice if you didn't have to convert each of the color components in the hex code to its corresponding RGB decimal value? Here's where a simple and very useful macro comes into play. Just place the code below in a header file and you're done. (They're identical except that UIColorFromRGB always sets the alpha value to 1.0, whereas UIColorFromRGBWithAlpha allows you to set the alpha value.)

?
1
2
3
4
5
6
7
8
9
10
11
//RGB color macro
#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]
 
//RGB color macro with alpha
#define UIColorFromRGBWithAlpha(rgbValue,a) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:a]

Here's how to call the macros:
?
1
2
self.view.backgroundColor = UIColorFromRGB(0xCECECE);
self.view.backgroundColor = UIColorFromRGBWithAlpha(0xCECECE, 0.8);

This is a good one to keep in your toolbox. Hope it's as useful for you as it is for me.

No comments:

Post a Comment