R – How to ‘Flatten’ multiple UIImageViews into ONE

core-graphicsflatteniphonepixeluiimage

I have a feeling this is not an easy task but I need to combine or flatten a UIImageView with another UIImage view lying above it. For example: I have two UIImageViews. One of them has a UIImage of a grassy field (1200 x 1200 pixels). The other is a UIImage of a basketball (128 x 128 pixels), and it is positioned above the image of the grassy field in such a way that the basketball appears to be on the grassy field. I want to be able to SAVE the superimposed UIImageViews as a single image file to my photo album which means that I will need to combine the two images somehow. How would this be accomplished? (NOTE: Taking a screenshot (320 x 480 pixels) would not be an acceptable solution as I wish to preserve the size of 1200 x 1600 pixels.

QUESTION:
How can I flatten multiple UIImageViews into one and SAVE the resulting image while preserving the size/resolution.

Best Answer

This takes any view and makes a UIImage out of it. Any view and it's subviews will be "flattened" into a UIImage that you can display or save to disk.

  - (UIImage*)imageFromView{

    UIImage *image;

    UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;

}
Related Topic