Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect color under mouse (Mac)

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?

like image 270
daniel Avatar asked Jul 31 '12 18:07

daniel


People also ask

How do you find the exact color on a Mac?

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.

Does Mac Have a color picker?

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.

How do I find the color code of an image on a Mac?

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.


1 Answers

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;
}
like image 91
Matt Wilding Avatar answered Sep 30 '22 16:09

Matt Wilding