Detect color under mouse (Mac)

十年热恋 提交于 2019-12-18 17:27:02

问题


i've been searching the web for more than hours and didn't find anything.

I want to know how to get the color of the pixel where the mouse pointer currently is. I programmed a console application, so I have no window to overlay or something else.

Just more detail: When I build&run the program ( cmd+r ), it should give me a console log of the color where my mouse pointer currently is. Is that possible?

Thank you for your answers!

Greetings, Daniel

PS: I'm from germany, just saying (language mistakes)


回答1:


Using this question and answer as a starting point, this is a fully functional command line program. You also need to link to the 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;
}

If you want to to keep running you'll need to take additional measures to create and drive a run loop.



来源:https://stackoverflow.com/questions/11746471/detect-color-under-mouse-mac

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