Search code examples
iosobjective-cuiviewuiimagecalayer

Capturing Screenshot of UIVIew with multiple CALayers displays white background while save image in gallery


I have a UIView with different CALayers with different size.

When I am trying to save UIView as image to gallery it looses its transparency:

My code is:

- (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

//Getting image

 UIImage *img=[self imageWithView:MainView];
 UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil);

Note:When I debug the code, it displays transparent image, but when I see in gallery it displays with white Background


Solution

  • I've tried your code. You can try following implementation:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        UIView *tmpView = [UIView new];
        tmpView.frame = self.view.bounds;
        tmpView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:tmpView];
    
        UIImage *img = [self imageWithView:tmpView];
        [self saveInJPGFormat:img];
        [self saveInPNGFormat:img];
    }
    
    - (void)saveInJPGFormat:(UIImage *)image {
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    
    - (void)saveInPNGFormat:(UIImage *)image {
        NSData* imageData =  UIImagePNGRepresentation(image);
        UIImage* pngImage = [UIImage imageWithData:imageData];
        UIImageWriteToSavedPhotosAlbum(pngImage, nil, nil, nil);
    }
    
    - (UIImage *) imageWithView:(UIView *)view {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
        [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
    

    Your method saves as JPG to camera roll. JPGs aren't capable to keep alpha channel. Second method taken from https://stackoverflow.com/a/10279075/849616 saves image as PNG. I can open it and I can see through the image (alpha channel is saved).

    BTW: ofc that's very dirty and quick code. In reality you should do a category on UIImage for these methods. Also keep MVC and either views&layers stick to storyboards or to separate UIView subclass.

    Images from my photo gallery: CameraRoll Screen of preview so you're sure it's empty: enter image description here

    So the method is working.