I hope that title makes some sense.
I have UIView (created in IB) where I add stuff (images). Then, I have a UILabel with some text. Now, I want to make a UIImage out of that, which I do like this:
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.previewView and self.lblCaption are both created in IB. previewView is just a screen-filling view.
The code-block is executed in an IBAction after a button-tap.
Which works wonderful, I get the image as expected and can process it further.
But after that, the contents of «self.previewView» are gone? When I do an NSLog, everything seems to be there, but it’s not visible on screen anymore.
Does anyone have an idea what’s going on here?
[Edit]
As the answer below states, the view was added to self.view before, so it was removed when I added it to the comp. The solution is pretty easy, actually, I changed the code to the following: (created a function that returns a UIImage. That’s a bit cleaner than doing it in code….
-(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;
}
I am just guessing assuming possible situations…
Assuming you were showing
self.previewViewon some other view, sayself.view.When you added
self.previewViewtocomp, it may have been removed fromself.view. (Considering that UIView.superview is only single instance, I am thinking this is very likely).If this is the case, re-adding
self.previewViewtoself.viewafter obtaining image would solve the problem.