I want to know how to get the color of the pixel where the OS X / macOS mouse pointer currently is located.
I programmed a console application, so I have no window to overlay or something else.
When I build and run the program, it should give me a console log of the color where my mouse pointer currently is. Is that possible?
Find the color value of any color on your screen. In the Digital Color Meter app on your Mac, do any of the following: Find the value of a color: Move the pointer over the pixels whose values you want to see. The color under the pointer is displayed in the Digital Color Meter window, with its color values on the right.
Just about every app on a Mac that has a color option uses a tool called the Color Picker. On my personal Mac, Color Picker is used in the following and in several other third-party apps: Mail.
You can easily copy the hex color code of any pixel on your Mac's screen using Digital Color Meter. To do this, make sure you have set the app to view hexadecimal values. Next, bring the mouse pointer on any screen color and press Command + Shift + C, and it will copy the hex color code to your clipboard.
Using this question and answer as a starting point, this is a fully functional command line program.
// To build and run, save this file as main.m, then:
//
// clang -framework Foundation -framework Cocoa main.m
// ./a.out
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
int main(int argc, const char *argv[]) {
CGDirectDisplayID mainDisplayID = CGMainDisplayID();
// NSLog(@"Main display id=%d", mainDisplayID);
while (true) {
@autoreleasepool {
CGPoint cursor = CGEventGetLocation(CGEventCreate(NULL));
// NSLog(@"Mouse pos: (%f, %f)", cursor.x, cursor.y);
CGRect rect = CGRectMake(cursor.x, cursor.y, 1, 1);
CGImageRef image = CGDisplayCreateImageForRect(mainDisplayID, rect);
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithCGImage:image];
CGImageRelease(image);
NSColor *color = [bitmap colorAtX:0 y:0];
NSLog(@"%@", color);
[bitmap release];
}
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With