UIWebView到UIImage

Vad*_*Vad 7 iphone xcode objective-c uiwebview

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

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

MQo*_*der 6

检查一下将UIWebView渲染到ImageContext中

或者只是使用这个:):

    (UIImage*) imageFromWebview:(UIWebView*) webview{

//store the original framesize to put it back after the snapshot
CGRect originalFrame = webview.frame;

//get the width and height of webpage using js (you might need to use another call, this doesn't work always)
int webViewHeight = [[webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] integerValue];
int webViewWidth = [[webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollWidth;"] integerValue];

//set the webview's frames to match the size of the page
[webview setFrame:CGRectMake(0, 0, webViewWidth, webViewHeight)];

//make the snapshot
UIGraphicsBeginImageContextWithOptions(webview.frame.size, false, 0.0);
[webview.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//set the webview's frame to the original size
[webview setFrame:originalFrame];

//and VOILA :)
return image;
}
Run Code Online (Sandbox Code Playgroud)


das*_*ght 4

编辑(来自Vad的评论)

解决方案是调用

webView.scalesPageToFit = YES;
Run Code Online (Sandbox Code Playgroud)

在初始化中,以及

[webView sizeToFit]
Run Code Online (Sandbox Code Playgroud)

当页面完成加载时。

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

UIView有一个scrollView属性 has contentSize,告诉您滚动视图内的 Web 视图的大小是多少。您可以使用该大小来设置图像上下文,如下所示:

-(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;
}
Run Code Online (Sandbox Code Playgroud)