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

I am trying to create an application for choosing cocoa color in objective-c so that I can get the color of any pixel on my screen. Is there a way to get the color of a specific pixel of the screen in objective-c?

+4
source share
2 answers

You can use CGDisplayCreateImageForRect to get a CGImageRef that spans the point of interest to you. After you have CGImage, you can get the color value from it by providing the image in a custom buffer or using NSBitmapImageRep initWithCGImage and then colorAtX: y :. The code "written on the code overflow code stack" for the NSBitmapImageRep method will look something like this:

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];
}

This will likely return the color in the color space of the device. It might be useful to return the color to the calibrated RBG color space.

+13
source

NSReadPixel. . , , .

0

All Articles