美文网首页
iOS-webView截图

iOS-webView截图

作者: Freedom_fly | 来源:发表于2017-09-13 10:26 被阅读315次
lp.jpg

开发中如何截图,webView为例,用法如下:

(一)截取当前屏幕显示的区域(设备的全屏)

代码如下:

    CGSize size = self.view.frame.size; 
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(viewImage, self, nil, nil);  //保存到相册中
(二)截取webView所有显示内容的区域

客户提出相关需求,需要截图当前webview所展示的所有的内容,代码如下:

    UIScrollView *scroll = (UIScrollView *)_webView;
    CGRect frame = scroll.frame;
    CGRect frame1 = scroll.frame; // 备份frame
    frame.size.height = _webView.scrollView.contentSize.height;
    scroll.frame = frame;
  
 UIGraphicsBeginImageContextWithOptions(CGSizeMake(iChe_ViewFrame.size.width,frame.size.height), YES, 0);     //设置截屏大小
    [scroll.layer renderInContext:UIGraphicsGetCurrentContext()];
    viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef imageRef = viewImage.CGImage;
    UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRef];
    UIImageWriteToSavedPhotosAlbum(sendImage, nil, nil, nil);//保存图片到照片库
    
    // 恢复frame 不然滑动没效果
    scroll.frame = frame1;

解释:
1、初始没有截图的时候,如果UIScrollView的高度不等于webView.scrollView.contentSize.height,后期截图的结果就是图片的高度是对的,但是只有只有当前屏幕展示的内容,其他展示不到的都是黑屏。
2、截图修改了frame的高度,截图完毕之后如果不恢复之前的高度,是看不到滑动效果的,因为UIScrollView高度大于你的设备的屏幕高。

注意:
为避免内存泄漏,UIGraphicsBeginImageContextWithOptionsUIGraphicsEndImageContext需成对出现。

资料:
UIGraphicsBeginImageContext 和 UIGraphicsBeginImageContextWithOptions

相关文章

网友评论

      本文标题:iOS-webView截图

      本文链接:https://www.haomeiwen.com/subject/hidksxtx.html