如何使用 Cocoa 和 CGDisplayCreateImageForRect 在 Mac OS X 中截取区域截图?
Posted
技术标签:
【中文标题】如何使用 Cocoa 和 CGDisplayCreateImageForRect 在 Mac OS X 中截取区域截图?【英文标题】:How to take region screenshot in Mac OS X using Cocoa and CGDisplayCreateImageForRect? 【发布时间】:2012-10-10 15:53:29 【问题描述】:我找到了如何制作全尺寸截图How to take screenshot in Mac OS X using Cocoa or C++,但是我如何制作区域截图?
【问题讨论】:
先阅读documentation for CGDisplayCreateImageForRect,然后问一个更具体的问题... 我知道。 CGDisplayCreateImageForRect如何获取鼠标坐标? 【参考方案1】:抱歉,格式很丑。第二个函数正是你想要的。
// this is a cute function for creating CGImageRef from NSImage.
// I found it somewhere on SO but I do not remember the link, I am sorry..
CGImageRef CGImageCreateWithNSImage(NSImage *image)
NSSize imageSize = [image size];
CGContextRef bitmapContext = CGBitmapContextCreate(NULL, imageSize.width, imageSize.height, 8, 0, [[NSColorSpace genericRGBColorSpace] CGColorSpace], kCGBitmapByteOrder32Host|kCGImageAlphaPremultipliedFirst);
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:bitmapContext flipped:NO]];
[image drawInRect:NSMakeRect(0, 0, imageSize.width, imageSize.height) fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
[NSGraphicsContext restoreGraphicsState];
CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);
CGContextRelease(bitmapContext);
return cgImage;
NSImage* NSImageFromScreenWithRect(CGRect rect)
// copy screenshot to clipboard, works on OS X only..
system("screencapture -c -x");
// get NSImage from clipboard..
NSImage *imageFromClipboard=[[NSImage alloc]initWithPasteboard:[NSPasteboard generalPasteboard]];
// get CGImageRef from NSImage for further cutting..
CGImageRef screenShotImage=CGImageCreateWithNSImage(imageFromClipboard);
// cut desired subimage from fullscreen screenshot..
CGImageRef screenShotCenter=CGImageCreateWithImageInRect(screenShotImage,rect);
// create NSImage from CGImageRef..
NSImage *resultImage=[[NSImage alloc]initWithCGImage:screenShotCenter size:rect.size];
// release CGImageRefs cause ARC has no effect on them..
CGImageRelease(screenShotCenter);
CGImageRelease(screenShotImage);
return resultImage;
【讨论】:
以上是关于如何使用 Cocoa 和 CGDisplayCreateImageForRect 在 Mac OS X 中截取区域截图?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Cocoa 和 CGDisplayCreateImageForRect 在 Mac OS X 中截取区域截图?
如何使用 Storyboards/Cocoa 在 Swift 3.x 中引用视图的窗口