项目中遇到截屏功能的实现
2018-05-17 本文已影响3人
iOSCoder
截屏方式分为两种:
- 截取当前屏幕全屏
- 对指定区域view进行截取
1、截取当前屏幕全屏的实现方法
#pragma mark -----截取当前屏幕全屏-----
- (UIImage *)snapshotCurrentFullScreen{
// 判断是否为retina屏, 即retina屏绘图时有放大因子
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]){
UIGraphicsBeginImageContextWithOptions(self.view.window.bounds.size, NO, [UIScreen mainScreen].scale);
} else {
UIGraphicsBeginImageContext(self.view.window.bounds.size);
}
[self.view.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// 保存到相册
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
return image;
}
2、对指定区域view进行截取实现方法
#pragma mark -----截取屏幕指定区域view-----
- (UIImage *)snapshotScreenInView:(UIView *)contentView{
CGSize size = contentView.bounds.size;
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
CGRect rect = contentView.bounds;
// 自iOS7开始,UIView类提供了一个方法-drawViewHierarchyInRect:afterScreenUpdates: 它允许你截取一个UIView或者其子类中的内容,并且以位图的形式(bitmap)保存到UIImage中
[contentView drawViewHierarchyInRect:rect afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
return image;
}