Detect color under mouse (Mac)

后端 未结 1 1663
情书的邮戳
情书的邮戳 2021-01-03 07:18

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

相关标签:
1条回答
  • 2021-01-03 08:07

    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.

    0 讨论(0)
提交回复
热议问题