c可可应用程序中获取屏幕上一个像素的颜色

c可可应用程序中获取屏幕上一个像素的颜色

本文介绍了在objective-c可可应用程序中获取屏幕上一个像素的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Objective-c 中创建一个颜色选择器可可应用程序,以便我可以获取屏幕上任何像素的颜色.有没有办法在objective-c中获得某个屏幕像素的颜色?

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?

推荐答案

您可以使用 CGDisplayCreateImageForRect 来获取包含您感兴趣的点的 CGImageRef.一旦您拥有 CGImage,您就可以从中获取颜色值通过将图像渲染到自定义缓冲区,或使用 NSBitmapImageRep 的 initWithCGImage 和 colorAtX:y:.NSBitmapImageRep 方法的在堆栈溢出代码窗口中编写"代码如下所示:

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

这可能会返回设备颜色空间中的颜色.改为在校准后的 RBG 颜色空间中返回颜色可能会很有用.

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

这篇关于在objective-c可可应用程序中获取屏幕上一个像素的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:04