1

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
Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
aloo
  • 5,331
  • 7
  • 55
  • 94

1 Answers1

5

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.

Benjie
  • 7,701
  • 5
  • 29
  • 44
adamkrell
  • 258
  • 1
  • 2
  • 11
  • I am also stuck at this point.could you please explain your answer in more detail.Or provide a sample source code please – Rahul Vyas Sep 29 '09 at 08:45
  • I'm not sure what information you need. Could you explain further where you're having difficulty? – adamkrell Oct 26 '09 at 15:54
  • `UIGraphicsBeginImageContext(myDrawView.bounds.size) myDrawView.drawViewHierarchyInRect(myDrawView.bounds, afterScreenUpdates: true) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil)` It doesn't save it as a PNG – DanielZanchi Apr 26 '16 at 17:47