Search code examples
iphoneioscocoa-touchuiimageuigraphicscontext

Maintain image resolution in screen grab


In my app, the user is able to put stickers on top of a photo. When they go to save their creation, I do a screen grab and store it in a UIImage:

UIGraphicsBeginImageContextWithOptions(self.mainView.bounds.size, NO, [UIScreen mainScreen].scale);
[self.mainView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultImage = [UIGraphicsGetImageFromCurrentImageContext() retain];
UIGraphicsEndImageContext();

(where self.mainView has a subview UIImageView which holds the photo, and another subview UIView which holds the stickers).

I am wondering, is it possible to do a screen shot in this manner, and maintain the resolution of the aforementioned photo?


Solution

  • The following will 'flatten' two UIImages into one while maintaining the resolution of the original image(s):

    CGSize photoSize = photoImage.size;
    UIGraphicsBeginImageContextWithOptions(photoSize, NO, 0.0);
    
    CGRect photoRect = CGRectMake(0, 0, photoSize.width, photoSize.height);
    // Add the original photo into the context
    [photoImage drawInRect:photoRect];
    // Add the sticker image with its upper left corner set to where the user placed it
    [stickerImage drawAtPoint:stickerView.frame.origin];
    
    // Get the resulting 'flattened' image
    UIImage *flattenedImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    

    The above assumes photoImage and stickerImage are both instances of UIImage and stickerView is a UIView with containing the stickerImage and thus will be able to use the stickerView frame to determine its origin.

    If you have multiple stickers, just iterate through the collection.