在 macOS 鼠标光标下检测颜色

7

我想知道如何获取鼠标指针当前所在位置的像素颜色,与OS X / macOS有关的。

我编写了一个控制台应用程序,因此没有窗口可以叠加或其他什么东西。

当我构建和运行程序时,它应该给我一个控制台日志,显示鼠标指针当前所在位置的颜色。这可能吗?

1个回答

12

这个问题和答案为起点,这是一个完全功能的命令行程序。

// 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;
}

哇,非常感谢!这正是我正在寻找的!再次感谢;-)但是,释放位图在释放池中,这真的有必要吗? - daniel
1
这是必要的,因为在这个例子中位图没有被自动释放。它是alloc'd。@autoreleasepool只会释放自动释放的对象。 - Matt Wilding
说句实话,对我来说坐标系统不匹配。我必须执行... mouseLoc = {screenHeight} - mouseLoc.y + 20; - whooops
1
通过将CGEventCreate(null)传递到CGEventGetLocation中来获取鼠标位置,将以正确的坐标系给出。顺便提一下,NS和CG使用不同的坐标系统。 - owencm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接