Skip to content

Instantly share code, notes, and snippets.

@adanmayer
Created October 17, 2012 16:41
Show Gist options
  • Save adanmayer/3906628 to your computer and use it in GitHub Desktop.
Save adanmayer/3906628 to your computer and use it in GitHub Desktop.
SRGB extensions for NSColor for OSX 10.6 and below
//
// NSColor+NSColor_sRGB.h
//
// Created by Alexander Danmayer on 10/17/12.
// Copyright (c) 2012 Alexander Danmayer. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface NSColor (NSColor_sRGB)
@end
//
// NSColor+NSColor_sRGB.m
//
// Created by Alexander Danmayer on 10/17/12.
// Copyright (c) 2012 Alexander Danmayer. All rights reserved.
//
#import <objc/runtime.h>
#import "NSColor+NSColor_sRGB.h"
id _colorSRGB (id self, SEL _cmd, CGFloat red, CGFloat green, CGFloat blue, CGFloat alpha)
{
CGFloat comps[4] = {red, green, blue, alpha};
return [NSColor colorWithColorSpace:[NSColorSpace sRGBColorSpace] components:comps count:4];
};
@implementation NSColor (NSColor_sRGB)
+ (BOOL)resolveClassMethod:(SEL)sel
{
if (sel == @selector(colorWithSRGBRed:green:blue:alpha:))
return YES;
return [super resolveInstanceMethod:sel];
}
+ (void) load {
// check if SRGB method is available ...
if ([NSColor resolveClassMethod:@selector(colorWithSRGBRed:green:blue:alpha:)])
{
// get the signature of a similar method
Method m = class_getClassMethod([NSColor class], @selector(colorWithCalibratedRed:green:blue:alpha:));
const char *code = method_getTypeEncoding(m);
// retrieve meta class for class methods
Class selfMetaClass = objc_getMetaClass([[self className] UTF8String]);
class_addMethod(selfMetaClass, @selector(colorWithSRGBRed:green:blue:alpha:), (IMP) _colorSRGB, code);
}
}
@end
@adanmayer
Copy link
Author

Example:

#import "NSColor+NSColor_sRGB.h"

...

- (void)drawSomething
{
   // This also works on 10.6 and below now
   NSColor *color = [NSColor colorWithSRGBRed:0.420 green:0.333 blue:0.396 alpha:1];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment