- (void)takeScreenShot {
CGImageRef screenShot = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);
CGImageWriteToFile(screenShot, [@"~/code/screenshot.png" stringByExpandingTildeInPath]);
}
BOOL CGImageWriteToFile(CGImageRef image, NSString *path) {
CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);
if (!destination) {
NSLog(@"Failed to create CGImageDestination for %@", path);
return NO;
}
CGImageDestinationAddImage(destination, image, nil);
if (!CGImageDestinationFinalize(destination)) {
NSLog(@"Failed to write image to %@", path);
CFRelease(destination);
return NO;
}
CFRelease(destination);
return YES;
}
無法爲 創建CGImageDestination /Users/"username"/Library/Containers/"bundleidentifier"/Data/code/screenshot.png如何將CGImageRef寫入png文件。 CGImageDestinationCreateWithURL返回nil
所以沒有返回目的地。 最好我想寫〜/ code/screenshot.png,但如果它是沙盒的東西,也可以寫入「沙箱」
如何將屏幕截圖寫入一個我可以稍後訪問的文件?
我從Saving CGImageRef to a png file?
這不是屬於沙盒應用程序的文件夾的有效路徑。 –
啊是的。將路徑更改爲@「screenshot.png」使其成功存儲圖像。 – user12345625