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

六眼飞鱼酱① 提交于 2019-12-17 17:59:18

问题


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?


回答1:


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.




回答2:


Try NSReadPixel. You'll need to get the current mouse location and convert it to the appropriate coordinate reference frame. Once you have the color, you might need to convert it to a different color space, depending on your needs.



来源:https://stackoverflow.com/questions/4395420/get-the-color-a-pixel-on-the-screen-in-objective-c-cocoa-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!