2013-03-28 18 views
1

在我的应用程序中,我想呈现一个UIView到UIImage视图。我用这个苹果的示例代码,可以在这里找到:https://developer.apple.com/library/ios/#qa/qa2010/qa1703.htmliOS的UIView呈现UIImage - 苹果的示例代码只能工作一次

- (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文本,上面的函数将返回与上一次相同的图像。 我检查了标签的文字确实发生了变化。但仍然渲染的图像不显示更改。

任何想法为什么发生这种情况?

感谢您的帮助! 真诚,

佐利

回答

0

苹果的代码是好的。尝试搜索你自己的代码的问题。我可以问几个问题来帮助你找到你的错。

也许您正在查看旧图像两次而不是正确设置新图像? 也许你在标签文字改变之前采取截图?

希望有所帮助。

0

我在这里只建议不要在代码中恢复CGState。这可能是问题....

也许你可以尝试绘制的NSString到图像,比折叠图像 看到这个帖子How to draw NSString

但是还是我的问题是: 你怎么能有更多的一个应用程序内的一个窗口? 常用的是在其中有一个窗口和更多的视图...? 那么为什么你需要使用更多的窗口?

另一个问题是你使用的最后一个窗口也是包含你想要显示的文本的窗口?因为你只是撤回最后一个窗口。

想象û有3次: 一个是黑色 一个是蓝色 一个是白色

如果您遍历它们,并将它们渲染成层,最后一个是白 - >您将得到只有白色一。因为另外两个是在最后一个下面渲染的。

那么,你的窗口是最高的?

Othewise我不明白,但绝对可以用这个片段

UIGraphicsBeginImageContext(view.frame.size); 
[view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

你会注意到,实例方法没有找到,但它的存在。

您还需要导入QuartzCore。

+0

嗨!感谢长时间的答复。但是,该代码也不起作用。我有几个意见,因为我只创建一个viewcontroller,所以我可以将其布局导出到图像。 viewcontroller将永远不可见。它会被创建,修改,而不会被删除。 –