UIColor macros for Objective-C

Tue, Oct 29

Below are two macros I paste into most every project. Besides saving a few keystrokes, they work well when using the color picker application. Let’s look at the macros first:

#define RGB(r, g, b) 
    [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]
#define RGBA(r, g, b, a) 
    [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:a]

Here’s the code without/with the macro:

// Code without the macro
  msgLabel.textColor = 
     [UIColor colorWithRed:255/255.0 green:251/255.0 blue:204/255.0 alpha:1];
 
  // Or like this...
  msgLabel.textColor = [UIColor colorWithRed:1.0 green:.98 blue:.8 alpha:1];
 
 // Code with macro
  msgLabel.textColor = RGB(255, 251, 204);

UIColor expects its parameters to be expressed as values in the range of 0.0 to 1.0, so I pass in the color value I’m looking for between 0 and 255, and let the macro do the math for me.

Let me show you how I use the macro with the color picker application. The figure below shows a screenshot of the color picker – at this point I have selected the color I am interested in, so I choose rgb from the dropdown menu.

From here, I copy the value from the field “Hex:”, paste this into my project and finish by changing rgb to RGB.

One comment

I made a little Objective-C category that makes it easy to use hex values: https://gist.github.com/kristopherjohnson/5606209

by Kristopher Johnson on Oct 29, 2013. #