gpt4 book ai didi

objective-c - 如何使用 Cocoa 和 CGDisplayCreateImageForRect 在 Mac OS X 中截取区域屏幕截图?

转载 作者:行者123 更新时间:2023-12-02 22:27:01 27 4
gpt4 key购买 nike

如何使用 Cocoa 和 CGDisplayCreateImageForRect 在 Mac OS X 中进行区域截图?我找到了如何制作全尺寸屏幕截图 How to take screenshot in Mac OS X using Cocoa or C++ , 但我如何制作区域截图?

最佳答案

抱歉格式丑陋。第二个函数完全符合您的要求。

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

关于objective-c - 如何使用 Cocoa 和 CGDisplayCreateImageForRect 在 Mac OS X 中截取区域屏幕截图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12823489/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com