snapshotViewAfterScreenUpdates:方法在iPhone7模拟器上返回一个空白view
在应用中需要用到截图操作,之前一直用snapshotViewAfterScreenUpdates快速获取一个截图,但是在iphone7模拟器上运行的时候直接截出了一个空白页,看网上有人说ios10之后snapshotViewAfterScreenUpdates这个方法失效,但是在iphone6plus真机上ios10跑过都没有问题,所以考虑是iphone7的问题;要换成绘图的方式来获取截图
改成如下代码在iphone7模拟器上也可以正常的截图了:
- (UIView *)customSnapshotFromView:(UIView *)inputView {
UIImage *image = [self imageFromView:inputView];
UIImageView *imgView = [[UIImageView alloc]initWithImage:image];
UIView *snapshot1 = imgView;
// UIView *snapshot1 = [inputView snapshotViewAfterScreenUpdates:YES];
snapshot1.layer.masksToBounds = NO;
snapshot1.layer.cornerRadius = 0.0;
snapshot1.layer.shadowOffset = CGSizeMake(5.0, 5.0);
snapshot1.layer.shadowRadius = 1.0;
snapshot1.layer.shadowOpacity = 0.4;
return snapshot1;
}
- (UIImage *)imageFromView:(UIView *)snapView {
// UIGraphicsBeginImageContext(snapView.frame.size);
UIGraphicsBeginImageContextWithOptions(snapView.frame.size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
[snapView.layer renderInContext:context];
UIImage *targetImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return targetImage;
}
用这个方法UIGraphicsBeginImageContext(snapView.frame.size); 不支持Retina屏幕(截出来的图片有些失真),所以用UIGraphicsBeginImageContextWithOptions(snapView.frame.size, NO, [UIScreen mainScreen].scale);
UIGraphicsBeginImageContext 和 UIGraphicsBeginImageContextWithOptions的比较
UIGraphicsBeginImageContext
创建一个基于位图的上下文(context),并将其设置为当前上下文(context)。方法声明如下:
void UIGraphicsBeginImageContext(CGSize size);
参数size为新创建的位图上下文的大小。它同时是由UIGraphicsGetImageFromCurrentImageContext函数返回的图形大小。
该函数的功能同UIGraphicsBeginImageContextWithOptions的功能相同,相当与UIGraphicsBeginImageContextWithOptions的opaque参数为NO,scale因子为1.0。
UIGraphicsBeginImageContextWithOptions
函数原型为:
void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);
size——同UIGraphicsBeginImageContext
opaque—透明开关,如果图形完全不用透明,设置为YES以优化位图的存储。
scale—–缩放因子 iPhone 4是2.0,其他是1.0。虽然这里可以用[UIScreen mainScreen].scale来获取,但实际上设为0后,系统就会自动设置正确的比例了。