Search code examples
iospngtransparent

save UIView as png file with transparent background


[[[globalSingleton paintingView] drawingView] setOpaque:NO];
[[[[globalSingleton paintingView] drawingView] layer] setOpaque:NO];    
[[[globalSingleton paintingView] drawingView] setBackgroundColor:[UIColor clearColor]];
[[[[globalSingleton paintingView] drawingView] layer] setBackgroundColor:[UIColor clearColor].CGColor];

[[[[globalSingleton paintingView] drawingView] layer] renderInContext:ctx];

UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();

The code above is what I'm using to save my 'drawingView' to a png file. I found several questions and answers, so I applied them. I set the opaque of my 'drawingView' and drawingView.layer as NO, and set the background color of my 'drawingView' as [UIColor clearColor]. I think I applied all answers from stackoverflow. However, there's nothing changed. The background of png fil is still black. I need transparent background, not black!!

I tried whether there's any problem with UIImage *image1. I used image1 to show on the screen, then I could find black background from that image1. So I could guess there is any problem when creating image1.

This is all I found. Is there any possible solution to save my png image with transparent background image? Thanks in advance!!


Solution

  • Oh, god! I did it!! I added [[UIColor clearColor] set]; . That's all.

    UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, [[UIScreen mainScreen] scale]);
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor clearColor] set];
    CGContextFillRect(ctx, screenRect);
    
    [[[globalSingleton paintingView] drawingView] setOpaque:NO];
    [[[[globalSingleton paintingView] drawingView] layer] setOpaque:NO];    
    [[[globalSingleton paintingView] drawingView] setBackgroundColor:[UIColor clearColor]];
    [[[[globalSingleton paintingView] drawingView] layer] setBackgroundColor:[UIColor clearColor].CGColor];
    
    [[[[globalSingleton paintingView] drawingView] layer] renderInContext:ctx]; 
    
    UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();