Skip to content

Instantly share code, notes, and snippets.

@jaanus
Last active August 29, 2015 14:03
Show Gist options
  • Save jaanus/4c07a2d575bab1eefa3f to your computer and use it in GitHub Desktop.
Save jaanus/4c07a2d575bab1eefa3f to your computer and use it in GitHub Desktop.
The easiest method to capture a PNG screenshot of NSWindow
@interface NSWindow (JKScreenShot)
- (NSData *)pngScreenshotData;
@end
@implementation NSWindow (JKScreenshot)
- (NSData *)pngScreenshotData
{
// This can be kCGWindowImageBoundsIgnoreFraming if you don’t want to include ornamentation like the shadow
CGWindowImageOption imageOptions = kCGWindowImageDefault;
CGWindowID windowID = (CGWindowID)[self windowNumber];
CGWindowListOption singleWindowListOptions = kCGWindowListOptionIncludingWindow;
CGRect imageBounds = CGRectNull;
CGImageRef windowImage = CGWindowListCreateImage(imageBounds, singleWindowListOptions, windowID, imageOptions);
NSBitmapImageRep *newRep = [[NSBitmapImageRep alloc] initWithCGImage:windowImage];
NSData *pngData = [newRep representationUsingType:NSPNGFileType properties:nil];
CFRelease(windowImage);
return pngData;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment