在iOS中获取可变高度webview的“屏幕截图”

时间:2013-10-16 12:37:20

标签: ios uiwebview webview screenshot

有人能指出一些示例代码来捕获嵌入在iphone应用程序中的完整webview的图像吗? webview的高度可变,具体取决于内容,因此简单的屏幕截图对用户不起作用,但我想在导航栏中为他们提供一个按钮,用于捕获全高图像并将其保存到他们的照片中图书馆。

提前致谢!

2 个答案:

答案 0 :(得分:0)

UIWebView显示UIScrollView上的内容时,您可以通过更改contentOffset的{​​{1}}参数并加入屏幕截图,从上到下开始制作屏幕截图。并且,请记得检查UIScrollView。祝你好运!

答案 1 :(得分:-2)

使用此代码:

    - (IBAction)buttonPressed:(id)sender 
{
    webViewHeight = [[self.myWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] integerValue];

CGRect screenRect = self.myWebView.frame;

double currentWebViewHeight = webViewHeight;
while (currentWebViewHeight > 0)
{
    imageName ++;

    UIGraphicsBeginImageContext(screenRect.size);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor blackColor] set];
    CGContextFillRect(ctx, screenRect);

    [self.myWebView.layer renderInContext:ctx];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",imageName]];

    if(currentWebViewHeight < 960)
    {
        CGRect lastImageRect = CGRectMake(0, 960 - currentWebViewHeight, self.myWebView.frame.size.width, currentWebViewHeight);
        CGImageRef lastImageRef = CGImageCreateWithImageInRect([newImage CGImage], lastImageRect);                
        newImage = [UIImage imageWithCGImage:lastImageRef]; 
        CGImageRelease(lastImageRef);
    }

    [UIImagePNGRepresentation(newImage) writeToFile:pngPath atomically:YES];

    [self.myWebView stringByEvaluatingJavaScriptFromString:@"window.scrollBy(0,960);"];
    currentWebViewHeight -= 960;
 }
 }