Skip to content

Instantly share code, notes, and snippets.

@msanders
Created November 20, 2010 16:11
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save msanders/707921 to your computer and use it in GitHub Desktop.
Save msanders/707921 to your computer and use it in GitHub Desktop.
Category for AppKit that converts an NSColor to a CGColor (ala UIColor in the iOS)
//
// NSColor+CGColor.m
//
// Created by Michael Sanders on 11/19/10.
//
#import <AppKit/AppKit.h>
@interface NSColor (CGColor)
//
// The Quartz color reference that corresponds to the receiver's color.
//
@property (nonatomic, readonly) CGColorRef CGColor;
//
// Converts a Quartz color reference to its NSColor equivalent.
//
+ (NSColor *)colorWithCGColor:(CGColorRef)color;
@end
//
// NSColor+CGColor.m
//
// Created by Michael Sanders on 11/19/10.
//
#import "NSColor+CGColor.h"
@implementation NSColor (CGColor)
- (CGColorRef)CGColor
{
const NSInteger numberOfComponents = [self numberOfComponents];
CGFloat components[numberOfComponents];
CGColorSpaceRef colorSpace = [[self colorSpace] CGColorSpace];
[self getComponents:(CGFloat *)&components];
return (CGColorRef)[(id)CGColorCreate(colorSpace, components) autorelease];
}
+ (NSColor *)colorWithCGColor:(CGColorRef)CGColor
{
if (CGColor == NULL) return nil;
return [NSColor colorWithCIColor:[CIColor colorWithCGColor:CGColor]];
}
@end
@petejkim
Copy link

To use under garbage collected environment:

replace

return (CGColorRef)[(id)CGColorCreate(colorSpace, components) autorelease];

with

#ifdef __OBJC_GC__  
return (CGColorRef)CFMakeCollectable(CGColorCreate(colorSpace, components));
#else
return (CGColorRef)[(id)CGColorCreate(colorSpace, components) autorelease];
#endif

@mralexgray
Copy link

how can we use this with ARC?

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