以编程方式拍摄屏幕快照时,视图中的UIImage没有保存-Objective-C

时间:2018-12-18 10:35:30

标签: ios objective-c

我正在尝试使用以下屏幕截图:

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    UIGraphicsBeginImageContextWithOptions(self.contentView.bounds.size, NO, [UIScreen mainScreen].scale);
} else {
    UIGraphicsBeginImageContext(self.contentView.bounds.size);
}

[self.contentView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

但是,保存的图像在屏幕快照中不包含图像(而是显示为白色)。为什么会这样?

任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

尝试一下

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
    UIGraphicsBeginImageContextWithOptions(self.image.bounds.size, NO, 2.0);
} else {
    UIGraphicsBeginImageContext(self.image.bounds.size);
}

[self.image drawViewHierarchyInRect:self.image.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(image);
if (imageData) {
    [imageData writeToFile:@"screenshot.png" atomically:YES];
} else {
    NSLog(@"error while taking screenshot");
}