美文网首页
iOS 通过截图实现分享 webView

iOS 通过截图实现分享 webView

作者: Hero_Guo | 来源:发表于2017-03-09 14:17 被阅读0次

前几天写项目的时候, 后台给返回的数据是 html 类型的一篇文章, 我将其通过 [webView loadHTMLString:htmlString baseURL:nil]的方式展示了出来,下面是效果图:

webView 加载 html 数据后的图片

但是当我用 UIActivityViewController (如果不知道苹果这个原生分享 API 的话, 可以点击这里)分享这篇文章时, 出现了问题, 怎么分享?
ActivityItems只可以是 image, string, 和 url, 一个 webView 我怎么分享呢? 席八...

嘿嘿后来想到一个办法, 就是把 webView 截图, 然后用 UIActivityViewController 分享image不就 OK 了.哈哈... 上代码:

- (UIImage *)imageRepresentation{
    
    CGSize boundsSize = self.view.bounds.size;
    CGFloat boundsWidth = self.view.bounds.size.width;
    CGFloat boundsHeight = self.view.bounds.size.height;
    
    CGPoint offset = self.webView.scrollView.contentOffset;
    
    CGFloat contentHeight = self.webView.scrollView.contentSize.height;
    
    // 可变数组
    NSMutableArray *images = [NSMutableArray array];
    
    while (contentHeight > 0) {
        
        // 截取整个 self.view
        UIGraphicsBeginImageContext(boundsSize);
        [self.webView.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        [images addObject:image];
        
        CGFloat offsetY = self.webView.scrollView.contentOffset.y;
        [self.webView.scrollView setContentOffset:CGPointMake(0, offsetY + boundsHeight)];
        contentHeight -= boundsHeight;
    }
    
    [self.webView.scrollView setContentOffset:offset];
    
    // 给 webView 截图UIGraphicsBeginImageContext(self.webView.frame.size);
    [images enumerateObjectsUsingBlock:^(UIImage *image, NSUInteger idx, BOOL *stop) {
        [image drawInRect:CGRectMake(0, boundsHeight * idx, boundsWidth, boundsHeight)];
    }];
    UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return fullImage;
}

通过调用上面的方法得到了如下截图:

对webView的截图

然后分享这张 image 就 OK 了.

如果你还有其他好的方法还望评论告知. 谢过了...

在这里看到一篇截图的文章, 希望对你有帮助

相关文章

网友评论

      本文标题:iOS 通过截图实现分享 webView

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