R – Converting a CGLayer to a *transparent* UIImage and PNG file in CoreGraphics iphone

core-graphicsiphoneuiimage

I've been making a simple painting app for the iphone. I'm trying to convert the drawn image to a transparent PNG (I don't want a white background). I'd also like to get a UIImage representation to use in a UIImageView.

Currently, I respond to touch events and draw paths to a CGLayer which is then drawn to my views context. I have access to both the CGLayer as well as the view itself. Currently, I output my view to an image using:

UIGraphicsBeginImageContext(drawingView.bounds.size);
[drawingView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();   
UIGraphicsEndImageContext();

This only uses the view to create a UIImage.

Since the view has a white background it is inluded in the UIImage I create. I'd like to get a UIImage that does not have this white background so I can display and write to a PNG file.

I think I should use the CGLayer I have directly but I'm not sure how to get that from the CGLayerRef type I have access to.

Any ideas would be much appreciated.

  • Aleem

Best Answer

I just dealt with this. Don't draw a background on the CGLayer and then set the background of the UIView to:

self.backgroundColor = [UIColor clearColor];

That should do it and your png will have a transparent background.