【问题标题】:How to take region screenshot in Mac OS X using Cocoa and CGDisplayCreateImageForRect?如何使用 Cocoa 和 CGDisplayCreateImageForRect 在 Mac OS X 中截取区域截图?
【发布时间】:2012-10-10 15:53:29
【问题描述】:

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

【问题讨论】:

标签: objective-c macos


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2010-09-07
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 2015-03-23
    相关资源
    最近更新 更多