简体   繁体   中英

How to take region screenshot in Mac OS X using Cocoa and CGDisplayCreateImageForRect?

How to take region screenshot in Mac OS X using Cocoa and CGDisplayCreateImageForRect? I found how to make a full size screenshot How to take screenshot in Mac OS X using Cocoa or C++ , but how I make region screenshot?

Sorry for ugly formatting. The second function does exactly what you want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM