UIWebView到UIImage [英] UIWebView to UIImage

查看:109
本文介绍了UIWebView到UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用此方法从UIWebView捕获图像,但图像仅包含屏幕的可见区域。如何捕获包含不可见区域的UIWebView的完整内容,即将整个网页合并为一个单独的图像?

I tried to capture image from UIWebView using this method but the image contains only visible area of the screen. How do I capture full content of UIWebView including invisible areas, i.e. the entire web page into one single image?

-(UIImage*)captureScreen:(UIView*) viewToCapture{
  UIGraphicsBeginImageContext(viewToCapture.bounds.size);
  [viewToCapture.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return viewImage;
}


推荐答案

编辑(来自 Vad 的评论)

解决方案是致电

webView.scalesPageToFit = YES;

[webView sizeToFit]

当页面完成加载时。

您当前只捕获可见部分,因为您将图像上下文限制为可见部分。你应该把它限制在可用的范围内。

You are currently capturing only the visible part because you are limiting the image context to what's visible. You should limit it to what's available.

UIView 有一个 scrollView 具有 contentSize 的属性,告诉您滚动视图中Web视图的大小。您可以使用该大小来设置图像上下文:

UIView has a scrollView property that has contentSize, telling you what is the size of the web view inside the scroll view. You can use that size to set your image context like this:

-(UIImage*)captureScreen:(UIView*) viewToCapture{
    CGSize overallSize = overallSize;
    UIGraphicsBeginImageContext(viewToCapture.scrollView.contentSize);
    // Save the current bounds
    CGRect tmp = viewToCapture.bounds;
    viewToCapture.bounds = CGRectMake(0, 0, overallSize.width, overallSize.height);
    // Wait for the view to finish loading.
    // This is not very nice, but it should work. A better approach would be
    // to use a delegate, and run the capturing on the did finish load event.
    while (viewToCapture.loading) {
         [NSThread sleepForTimeInterval:0.1];
    }
    [viewToCapture.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    // Restore the bounds
    viewToCapture.bounds = tmp;
    return viewImage;
}

这篇关于UIWebView到UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆