创建一个带有到子视图的新视图,获取图形上下文是否破坏原始视图



我希望这个标题有意义。

我有UIView(在IB中创建),在那里我添加东西(图像)。然后,我有一个带有一些文本的UILabel。现在,我想用它制作一个UIImage,我喜欢它:

UIView *comp = [[UIView alloc] initWithFrame:self.previewView.frame];
[comp addSubview:self.previewView];
[comp addSubview:self.lblCaption];
UIGraphicsBeginImageContextWithOptions(comp.bounds.size, NO, 1.0);
[comp.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.reviewView和self.lblCaption都是在IB中创建的。previewView只是一个屏幕填充视图。

点击按钮后,代码块在IBAction中执行。

这很好,我得到了预期的图像,可以进一步处理。

但在那之后,«self.previewView»的内容就不见了?当我做NSLog时,一切似乎都在那里,但它在屏幕上已经看不见了。

有人知道这里发生了什么吗?

[编辑]

正如下面的答案所示,该视图以前被添加到self.view中,所以当我将其添加到comp时,它被删除了。这个解决方案很简单,实际上,我把代码改成了如下:(创建了一个返回UIImage的函数。这比在代码中做要干净一些…

-(UIImage *)imageFromView:(UIView *)theView andLabel:(UILabel *)theLabel{
UIGraphicsBeginImageContextWithOptions(comp.bounds.size, NO, 1.0);
[theView.layer renderInContext:UIGraphicsGetCurrentContext()];
[theLabel.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}

我只是在猜测可能的情况。。。

假设您在其他视图中显示self.previewView,那么就说self.view

当您将self.previewView添加到comp时,它可能已从self.view中删除。(考虑到UIView.supview只是一个实例,我认为这很可能)。

如果是这种情况,则在获得图像之后将self.previewView重新添加到self.view将解决该问题。

最新更新