I have a hexadecimal color value and I want to convert it to a UIColor. UIColor can take in a Hue/Saturation/Brightness (HSB) value or a Red/Blue/Green (RGB) value. How can I use the hex value to create a UIColor?
5 Answers
There is a great free library that is basically just some add ons to UIColor here (i think this is the same thing I use, cant remember). Check it out to make sure, but I think it has what you are looking for.
Picked this up from somewhere a while back, it's been sitting in my macro header for all my projects for a while now.
To use: view.backgroundColor = UIColorFromRGB(0x2134b6)
//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]
See the answers to How can I create a UIColor from a hex string?
The basic concept is to take the red blue green segments of the hex string, divide them by 256, and there you have your [0, 1] red blue green values that UIColor needs.
Forget the HSB values, you don't need to make that conversion.
I'm not sure how your color value is encoded in the HEX value. But here's an example with RGB values. Let's say you have a HEX value encoded something like this hexRGB = 0xRRGGBB to assign it to a UIColor, all you would have to do is
[UIColor colorWithRed:(hexRGB & 0xFF0000 >> 16) green:(hexRGB & 0x00FF00 >> 8) blue:(hexRGB & 0x0000FF) alpha:1]
The same technique could be used if reading a HSB value from hex where the value is encoded: 0xHHSSBB
As others have mentioned your HEX values are probably RGB.
I needed to do this once for a method I found that created button highlights programmatically. The theory behind HSB (or HSV as it is also known) is discussed in great detail at wikipedia. All the mathematics of the color space is there so if implementing your own it's probably the place to start.
There's a nice, compact, simple implementation in C at Rochester Institute of Technology. You should be able to paste these functions in and use them directly.
(But if Erica Sadun wrote a category to provide this function in UIColor, use it. See Jesse Naugher's answer for link.)