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

标签 iphone ios uiwebview uiimage

我有一种方法可用于从我的 iOS 应用程序的各种 View 中获取图像,以便用户通过电子邮件发送屏幕。我绘制的大多数屏幕都工作正常,但是当我将此技术与 UIWebView 一起使用时,我只能获得屏幕的可见部分。渲染图像中不包含屏幕外的任何内容。一直在 Stack 上四处挖掘,但到目前为止我没有找到任何有用的东西?!

这是我目前使用的方法:

-(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 相关的东西……然后我想到,为什么不直接将上下文中的 View 设置为 sizeThatFits。成功了!

警告:不能保证您不会遇到内存问题,我确实建议您在@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
}

关于iphone - 如何从 UIWebView 获取整个图像,包括屏幕外内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9881442/

相关文章:

ios - 如何在 IOS 中找出滚动方向时也包括 ScrollView 的弹跳?

javascript - 使用 javascript 将大型 HTML 字符串加载到 UIWebView

iphone - 在哪里确定 UIView 大小

ios - 如果多个应用程序指向同一个域,通用链接不会显示应用程序选择菜单

iphone - 母语国家列表

ios - AIR iOS 应用程序中的文本 URL 不可选择

ios - 向上滚动后 UITableViewCell 高度变化?

objective-c - 带水平滚动的 PDF View

ios - <zip 文件> 中的应用程序没有包标识符

ios - 在 UITextView 中快速将 'Return' 按钮功能更改为 'Done'