Oct '09
15

I’ve been working a lot on adding useful macros to InScopeLib.

A while back I saw a cool color macro that converted 0-255 color values to 0-1, which is what is used in Cocoa. I was for the iPhone so used UIColor. I finally got around to writing my own and wanted to make the macro work on both the iPhone and the Mac. After some Googling I found all the pieces I needed!

#import "TargetConditionals.h"

#define TARGET_IPHONE (TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE)

#if TARGET_IPHONE
#define RGB_COLOR(r, g, b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0]
#define RGBA_COLOR(r, g, b, a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a/255.0]
#else
#define RGB_COLOR(r, g, b) [NSColor colorWithCalibratedRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0]
#define RGBA_COLOR(r, g, b, a) [NSColor colorWithCalibratedRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a/255.0]
#endif

#import “TargetConditionals.h”
TARGET_IPHONE_SIMULATOR and TARGET_OS_IPHONE are defined in #import “TargetConditionals.h”, which will only exist on Apple platforms so if you wanted to be safe you could call it like this:

#ifdef __APPLE__
  #import "TargetConditionals.h"
#endif

But this macro is all objective-c so I decided to leave this safety net out, if these macros are used on an non-apple platform there will be more problems then just not being able to find the header :)

#define TARGET_IPHONE (TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE)

  • TARGET_IPHONE_SIMULATOR: True if we are building for the simulator
  • TARGET_OS_IPHONE: True if we are building for the device

For this macro, and others, I only care if we are compiling for the iPhone. So if we are compiling for the simulator or device set TARGET_IPHONE to true.

#if TARGET_IPHONE

If this variable is true we are compiling for the iPhone, as described above.

UIColor vs NSColor

Besides the class names being different the methods are different too. UIColor uses colorWithRed:green:blue:alpha: and NSColor uses colorWithCalibratedRed:green:blue:alpha:.

RGB_COLOR & RGBA_COLOR

RGB_Color and RGBA_Color do basically the same thing, except RGBA_Color accepts an alpha value and RGB_Color always uses an alpha value of 1.

And there you have it…

An rgb color macro that will take 0-255 values, and work on the iPhone and mac!

Leave a Reply