Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the color a pixel on the screen in objective-c cocoa app

I am trying to create a color picker cocoa app in objective-c so I can get the color of any pixel on my screen. Is there a way to get the color a certain screen pixel in objective-c?

like image 453
Sarathi Avatar asked Dec 09 '10 06:12

Sarathi


1 Answers

You can use CGDisplayCreateImageForRect to get a CGImageRef that encompasses the point you're interested in. Once you have a CGImage, you can get a color value out of it by rendering the image into custom buffer, or by using NSBitmapImageRep's initWithCGImage and then colorAtX:y:. The "written in stack overflow code window" code for the NSBitmapImageRep method would look something like:

NSColor *MyColorAtScreenCoordinate(CGDirectDisplayID displayID, NSInteger x, NSInteger y) {
    CGImageRef image = CGDisplayCreateImageForRect(displayID, CGRectMake(x, y, 1, 1));
    NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithCGImage:image];
    CGImageRelease(image);
    NSColor *color = [bitmap colorAtX:0 y:0];
    [bitmap release];
}

That will probably return the color in device color space. It might be useful to return the color in calibrated RBG color space instead.

like image 143
Jon Hess Avatar answered Sep 24 '22 00:09

Jon Hess