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

但是当我用 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;
}
通过调用上面的方法得到了如下截图:

然后分享这张 image 就 OK 了.
如果你还有其他好的方法还望评论告知. 谢过了...
网友评论