我有一种方法可以从 iOS 应用程序中的各种视图获取图像,以便用户通过电子邮件发送屏幕。我绘制的大多数屏幕都工作正常,但是当我将这种技术与 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 相关的东西……然后我突然想到,为什么不将上下文中的视图设置为 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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)