在我的应用程序中,我希望将UIView的视图呈现为UIImage。我使用的是苹果的示例代码,可以在这里找到:https://developer.apple.com/library/ios/#qa/qa2010/qa1703.html
- (UIImage*)screenshot
{
// Create a graphics context with the target size
// On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration
// On iOS prior to 4, fall back to use UIGraphicsBeginImageContext
CGSize imageSize = [[UIScreen mainScreen] bounds].size;
if (NULL != UIGraphicsBeginImageContextWithOptions)
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
else
UIGraphicsBeginImageContext(imageSize);
CGContextRef context = UIGraphicsGetCurrentContext();
// Iterate over every window from back to front
for (UIWindow *window in [[UIApplication sharedApplication] windows])
{
if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])
{
// -renderInContext: renders in the coordinate space of the layer,
// so we must first apply the layer's geometry to the graphics context
CGContextSaveGState(context);
// Center the context around the window's anchor point
CGContextTranslateCTM(context, [window center].x, [window center].y);
// Apply the window's transform about the anchor point
CGContextConcatCTM(context, [window transform]);
// Offset by the portion of the bounds left of and above the anchor point
CGContextTranslateCTM(context,
-[window bounds].size.width * [[window layer] anchorPoint].x,
-[window bounds].size.height * [[window layer] anchorPoint].y);
// Render the layer hierarchy to the current context
[[window layer] renderInContext:context];
// Restore the context
CGContextRestoreGState(context);
}
}
// Retrieve the screenshot image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}第一次尝试时,它工作得很好。但如果稍后我修改了视图中的UILabel文本,上面的函数将返回与上次相同的图像。我检查了标签的文本确实发生了变化。但是渲染的图像仍然不会显示这些变化。
知道为什么会这样吗?
发布于 2013-03-28 23:44:14
苹果的代码没问题。尝试搜索您自己的代码以查找问题。我可以问几个问题来帮助你找出你的错误。
也许您正在查看旧图像两次,而不是正确设置新图像?也许你是在标签文本改变之前截图?
发布于 2013-03-29 00:18:25
我在这里唯一的建议是不要在你的代码中恢复CGState。这可能是问题所在..。
也许您可以尝试将nsstring绘制到图像中,然后折叠图像,请参阅此帖子How to draw NSString
但我的问题仍然是:你怎么能在一个应用程序中拥有多个窗口?常见的用法是有一个窗口和其中的多个视图。?那么为什么你需要使用更多的窗口呢?
另一个问题是你使用的最后一个窗口,也就是包含你想要显示的文本的窗口?因为您只检索最后一个窗口。
想象一下你有3个视图:一个是黑色的,一个是蓝色的,一个是白色的
如果你迭代它们并将它们渲染到层中,最后一个是白色的->,你将只得到白色的那个。因为另外两个是在最后一个下渲染的。
那么你的窗口是最上面的那个吗?
否则我就不明白了,但是你绝对可以使用这个代码片段
UIGraphicsBeginImageContext(view.frame.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();您将注意到,未找到实例方法,但它存在。
您还需要导入QuartzCore。
发布于 2013-10-14 23:16:44
确保在主线程中修改UILabel的text属性。
霍尔法尔的答案看起来是对的。iOS 7的更新是有一个新的应用程序接口来捕获视图的内容,你可能会有兴趣看看下面的片段。
http://ioscodesnippet.com/2011/08/25/rendering-any-uiviews-into-uiimage-in-one-line/
https://stackoverflow.com/questions/15685680
复制相似问题