Draw image from subview into superview

I apologise in advance, this is a difficult problem to explain. Essentially I'm trying to do the equivalent of Merge Layers in Photoshop where the background image is merged with all other images, and get a new background image as pointed out by Leo.

I have a set of UIViews inside the superView and inside each UIView is a UIImageView. The UIImageViews have CGAffineTransformations applied to them and if they become larger than the UIView, the UIView becomes larger to fit the UIImageView.

Ultimate Goal: save an image with all the UIImageViews + a background image.

So far I can successfully access each UIImageView using:

    for (id obj in self.view.subviews) {
        if ([obj isKindOfClass:[UIView class]] && [((UIView *)obj).subviews.firstObject isKindOfClass:[UIImageView class]]) {

            UIImageView *view = ((UIImageView *)((UIView *)obj).subviews.firstObject);

        }
    }

How can I combine these images with the background image and keep all their attributes.

Answers


To achieve this, you can use - (BOOL)drawViewHierarchyInRect:(CGRect)rect afterScreenUpdates:(BOOL)afterUpdates.

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:NO];
//The merged image.
UIImage * mergedBackground = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//Remove superviews as they are no longer required.
[self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

Need Your Help

iOS: Custom view with xib

ios cocoa-touch

I'm missing something important. Not exactly sure what it is.