Skip to content

Instantly share code, notes, and snippets.

@aquarius
Created April 9, 2013 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aquarius/5344499 to your computer and use it in GitHub Desktop.
Save aquarius/5344499 to your computer and use it in GitHub Desktop.
Convert any color into RGB
- (NSColor *)mn_rgbColor;
{
if ([[self colorSpaceName] isEqualToString:NSCalibratedRGBColorSpace]) return self;
// try to convert to RGB
NSColor *color = [self colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
if (color) return color;
// convert to image and extract first px. The result won't be 100% correct, but better than a completely undefined color
NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL pixelsWide:1 pixelsHigh:1 bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSCalibratedRGBColorSpace bytesPerRow:4 bitsPerPixel:32];
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmapRep];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:context];
[self setFill];
NSRectFill(CGRectMake(0, 0, 1, 1));
[context flushGraphics];
[NSGraphicsContext restoreGraphicsState];
NSColor *rgbColor = [bitmapRep colorAtX:0 y:0];
[bitmapRep release];
return rgbColor;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment