在鼠标下检测颜色(Mac)

dan*_*iel 4 macos colors objective-c detect

我一直在网上搜索超过几个小时,但没有找到任何东西.

我想知道如何获得鼠标指针当前所在像素的颜色.我编写了一个控制台应用程序,所以我没有窗口可以叠加或其他东西.

更多细节:当我构建并运行程序(cmd + r)时,它应该给我一个控制台日志,显示我的鼠标指针当前所在的颜色.那可能吗?

谢谢您的回答!

问候,丹尼尔

PS:我来自德国,只是说(语言错误)

Mat*_*ing 10

使用这个问题和答案作为起点,这是一个功能齐全的命令行程序.您还需要链接到Cocoa Framework.

#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {

        // Grab the current mouse location.
        NSPoint mouseLoc = [NSEvent mouseLocation];

        // Grab the display for said mouse location.
        uint32_t count = 0;
        CGDirectDisplayID displayForPoint;
        if (CGGetDisplaysWithPoint(NSPointToCGPoint(mouseLoc), 1, &displayForPoint, &count) != kCGErrorSuccess)
        {
            NSLog(@"Oops.");
            return 0;
        }

        // Grab the color on said display at said mouse location.
        CGImageRef image = CGDisplayCreateImageForRect(displayForPoint, CGRectMake(mouseLoc.x, mouseLoc.y, 1, 1));
        NSBitmapImageRep* bitmap = [[NSBitmapImageRep alloc] initWithCGImage:image];
        CGImageRelease(image);
        NSColor* color = [bitmap colorAtX:0 y:0];
        NSLog(@"%@", color);
        [bitmap release];
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果你想继续运行,你需要采取额外的措施来创建和驱动运行循环.