My preferred approach is to avoid UIColor
and NSColor
altogether, and simply use CGColorRef
wherever possible.
Core Animation is the best/most modern way to draw on both iOS and OS X. It expects CGColorRef
objects and is (pretty much) cross platform.
The only drawback is, being a lower level data type, ARC doesn't handle memory management for you. But manual memory management isn't that hard.
Usage of CGColorRef:
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGFloat componennts[4] = {255, 255, 255, 255}; // white, with 100% opacity. Use {0,0,0,255} for black, or {255,0,0,127.5} for red with 50% opacity.
CGColorRef color = CGColorCreate(colorSpace, componennts);
CGColorSpaceRelease(space);
layer.backgroundColor = color; // layer is a CALayer object
CGColorRelease(color);
You could avoid creating/releasing the color space object by storing it in a static variable:
static CGColorSpaceRef colorSpace;
@implementation MyClass
+ (void)initialize
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
colorSpace = CGColorSpaceCreateDeviceRGB();
});
}
- (void)blah
{
CGFloat componennts[4] = {255, 255, 255, 255}; // white, with 100% opacity. Use {0,0,0,255} for black, or {255,0,0,127.5} for red with 50% opacity.
CGColorRef color = CGColorCreate(space, componennts);
layer.backgroundColor = color; // layer is a CALayer object
CGColorRelease(color);