如何从UIWebView获取包含屏幕外内容的整体图像

Cli*_*udo 3 iphone uiwebview uiimage ios

我有一个方法用于从我的iOS应用程序中的各种视图中获取图像,以便让用户通过电子邮件发送屏幕.我绘制的大多数屏幕都工作正常,但是当我使用UIWebView的这种技术时,我只得到屏幕的可见部分.屏幕外的任何内容都不包含在渲染图像中.在堆栈上一直在这里挖掘,但到目前为止我找不到什么工作?!

这是我目前使用的方法:

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

Cli*_*udo 5

哇,答案很简单......正在挖掘整个地方,看着各种印刷/ PDF相关的东西......然后它发生在我身上,为什么不把环境中的视图设置为sizeThatFits.有效!

警告:不保证你不会遇到mem问题,我建议你在@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
}
Run Code Online (Sandbox Code Playgroud)