This question shows research effort; it is useful and clear
22
Save this question.
Show activity on this post.
I have a UIView that has an image and some buttons as its subviews. I'd like to get a "snapshot" image of it using renderInContext, or other method.
[clefView.layer renderInContext:mainViewContentContext];
If I pass it my UIView (as above) then I get a blank bitmap. None of the children are rendered into the bitmap.
If I pass it the child view that is the image, then I get an image of that bitmap, and, unsurprisingly, none of its siblings (buttons).
I was sort of hoping that renderInContext would take the image and all it's visible children and render it into a bitmap. Has anyone have any ideas how to do this?
14.3k20 gold badges90 silver badges138 bronze badges
Try something like this:
UIGraphicsBeginImageContext(clefView.bounds.size);
[clefView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
6 Comments
Thanks, but that didn't do it. I get the same results. The problem, I think, is that renderInContext isn't traversing the subviews and only doing the top layer that is passed to it (despite what I think it supposed to do). Do I have to call renderInContext for each subview?
Ok, playing with it a bit more and this is the right answer. My ImageContext was being set to a sibling view not a superview. Thanks!
|
The simple 4-line version didn't work for me. I have a UIView (with sublayers), and a child UITextView. I can render the UIView into the UIImage OK, but the child UITextView does not get rendered.
My simple solution is as follows:
CGRect rect = [view bounds];
UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[view.layer renderInContext:context];
for (UIView *sv in view.subviews)
{
CGContextTranslateCTM(context, sv.frame.origin.x, sv.frame.origin.y);
[sv.layer renderInContext:context];
CGContextTranslateCTM(context, -sv.frame.origin.x, -sv.frame.origin.y);
}
UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Note that the simple use of CGContextTranslateCTM assumes the child views have no transform other than translation. Also I'm assuming the child views are entirely contained within the parent view frame.
Comments
Explore related questions
See similar questions with these tags.