使用Objective c for mac的屏幕截图

Dan*_*iel 8 screen objective-c capture

有谁知道如何在mac os中使用目标c捕获屏幕?更具体地说,我如何捕获活动/聚焦应用程序屏幕,然后将图像创建到指定路径.
任何帮助都非常感谢.

ThE*_*FuL 8

@Daniel,你不需要理解和实现整个"掠夺之子".你只需要下面的代码.

以下功能将为您提供屏幕截图

// This just invokes the API as you would if you wanted to grab a screen shot. The equivalent using the UI would be to
// enable all windows, turn off "Fit Image Tightly", and then select all windows in the list.
CGImageRef screenShot = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);
Run Code Online (Sandbox Code Playgroud)

使用以下代码将其转换为NSImage

NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:screenShot];
// Create an NSImage and add the bitmap rep to it...
NSImage *image = [[NSImage alloc] init];
[image addRepresentation:bitmapRep];
[bitmapRep release];
bitmapRep = nil;
Run Code Online (Sandbox Code Playgroud)

  • 记得调用 `CFRelease(screenShot);` 以免泄露。 (2认同)

Ark*_*kku 4

您是否检查过 Apple 的Grab\xe2\x80\x9d 的 \xe2\x80\x9cSon来使用 CGWindow api 捕获窗口图像?

\n