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

标签 objective-c macos

如何使用 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/

相关文章:

objective-c - 在 NSString 对象中查找子字符串

objective-c - AFNetworking 如何检查上传操作是否完成或失败

iphone - @property 为 int 类型?

c++ - OSX 创建 C++ 内核扩展

macos - float 在 GNU smalltalk (gst) 中引发除零错误

ios - 在同一个 POST 中发送 NSData 和 NSString

ios - 应用程序非事件状态通知没有到达?

c++ - 无法在 MacOS Mojave 上链接 C++11 的库

multithreading - MPProcessors 在 Mac OS 10.7 中被弃用。还有什么选择?

python - 安装了 Nose 但不能在命令行上使用