Friday, July 30, 2010

UIColor macro with hex values

Cocoa has several colors built into the UIColor class. For example:
[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:
[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.)

//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:
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.

4 comments:

  1. Absolutely brilliant!
    Thanks a lot!
    Nacho

    ReplyDelete
  2. Your macros for UIColor from hex rgb values might be handy as a category on UIColor that could be used as follows:

    UIColor* color = [UIColor colorFromHexRGB:0xFF00FF];

    and

    UIColor* colorWithAlpha = [UIColor colorFromHexRGBA:0xFF00FF88];

    ReplyDelete
  3. Thank you for this!!! Exactly what I've been looking for!

    ReplyDelete
  4. For those who want to do it as a category of UIColor

    @implementation UIColor (Hex)

    //RGB color with alpha
    + (UIColor *)colorWithHex:(int)hexValue alpha:(CGFloat)alpha
    {
    return [UIColor
    colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0
    green:((float)((hexValue & 0xFF00) >> 8))/255.0
    blue:((float)(hexValue & 0xFF))/255.0 alpha:alpha];
    }


    //RGB color
    + (UIColor *)colorWithHex:(int)hexValue
    {
    return [UIColor colorWithHex:hexValue alpha:1.0];
    }

    @end

    ReplyDelete