如何从UIWebView获取整个图像,包括屏幕外的内容

我有一个方法,我用我的iOS应用程序中的各种视图来获取图像,让用户的电子邮件屏幕。 我画的大部分屏幕都可以正常工作,但是当我使用UIWebView的这种技术时,我只能看到屏幕的可见部分。 任何closures屏幕不包括在渲染的图像。 一直在这里挖堆栈,但到目前为止我find的东西没有作品?!

这是我目前使用的方法:

-(NSData *)getImageFromView:(UIView *)view { NSData *pngImg; CGFloat max, scale = 1.0; CGSize size = [view bounds].size; // Scale down larger images else we run into mem issues with mail widget max = (size.width > size.height) ? size.width : size.height; if( max > 960 ) scale = 960/max; UIGraphicsBeginImageContextWithOptions( size, YES, scale ); CGContextRef context = UIGraphicsGetCurrentContext(); [view.layer renderInContext:context]; pngImg = UIImagePNGRepresentation( UIGraphicsGetImageFromCurrentImageContext() ); UIGraphicsEndImageContext(); return pngImg; } 

哇,答案是愚蠢的简单…挖遍各地看各种印刷/ PDF相关的东西…然后它发生在我身上,为什么不只是把视图的背景设置为sizeThatFits。 有效!

警告:不能保证你不会遇到这个mem的问题,我build议你在@autoreleasepool池中这样做,并考虑做一些缩放,就像我在这个例子中做的那样,但是这个工作正是我所解决的:

 -(NSData *)getImageFromView:(UIView *)view // Mine is UIWebView but should work for any { NSData *pngImg; CGFloat max, scale = 1.0; CGSize viewSize = [view bounds].size; // Get the size of the the FULL Content, not just the bit that is visible CGSize size = [view sizeThatFits:CGSizeZero]; // Scale down if on iPad to something more reasonable max = (viewSize.width > viewSize.height) ? viewSize.width : viewSize.height; if( max > 960 ) scale = 960/max; UIGraphicsBeginImageContextWithOptions( size, YES, scale ); // Set the view to the FULL size of the content. [view setFrame: CGRectMake(0, 0, size.width, size.height)]; CGContextRef context = UIGraphicsGetCurrentContext(); [view.layer renderInContext:context]; pngImg = UIImagePNGRepresentation( UIGraphicsGetImageFromCurrentImageContext() ); UIGraphicsEndImageContext(); return pngImg; // Voila an image of the ENTIRE CONTENT, not just visible bit } 

我刚才为此创build了一个类别。 它的工作原理是,只有当Web视图被caching到内存中,否则页面的一部分将显示为白色。

 #import "UIWebView+Screenshot.h" #import <QuartzCore/QuartzCore.h> @implementation UIWebView (Screenshot) - (UIImage *)screenshot { UIImage *img = nil; UIGraphicsBeginImageContextWithOptions(self.scrollView.contentSize, self.scrollView.opaque, 0.0); { CGPoint savedContentOffset = self.scrollView.contentOffset; CGRect savedFrame = self.scrollView.frame; self.scrollView.contentOffset = CGPointZero; self.scrollView.frame = CGRectMake(0, 0, self.scrollView.contentSize.width, self.scrollView.contentSize.height); [self.scrollView.layer renderInContext: UIGraphicsGetCurrentContext()]; img = UIGraphicsGetImageFromCurrentImageContext(); self.scrollView.contentOffset = savedContentOffset; self.scrollView.frame = savedFrame; } UIGraphicsEndImageContext(); return img; } @end 

您可以放大uiwebview,使所有内容适合在屏幕上…但这只会在图像水平地离开屏幕时才起作用。 如果UIWebView比屏幕长,那么这不会有太大的帮助。

 [webview.scrollView setZoomScale:webview.scrollView.minimumZoomScale animated:NO];