Creating UIColor objects from hex values

It’s pretty inconvenient to create UIColor objects while developing apps for the iPhone, as you need to specific separate values for the RGB parts: red, green, blue.

I found a trick online a few weeks ago on how to automatically generate that code, by simply using a 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]

The usage looks something like this:

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (nil == cell) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"cell"] autorelease];
    }
    cell.textColor = UIColorFromRGB(0x333333);
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.text = @"Testing 1 2 3";
}

Hope that’s useful to someone.

4 Comments »

  1. Sahil said,

    December 7, 2008 @ 9:18 pm

    This is really great! thanks for putting it up, I’ve been trying to find something like this for a long time now. Combined with this (http://wafflesoftware.net/hexpicker/), it’s the easiest way to get concise colors.

  2. Ivan said,

    March 1, 2009 @ 8:54 am

    Thanks, this is very helpful.

    Cheers,
    Ivan

  3. Rodney Aiglstorfer said,

    March 1, 2009 @ 2:21 pm

    This is very helpful. Not being a C guy it would never have occured to me to create a macro to do this.

  4. Zachariah Cox said,

    August 10, 2009 @ 11:16 am

    thanks, I’m a java developer and macros are still kind of magical to me.

RSS feed for comments on this post · TrackBack URI

Leave a Comment