I want to create an UIImage
object from a UIView
. The view is NOT opaque.
for that i'm using the following code:
+ (UIImage *) imageWithView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, [[UIScreen mainScreen] scale]);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
But for some reason instead of transparent background i'm getting a image with black background.
I already tried to set the "opaque" parameter in UIGraphicsBeginImageContextWithOptions
to NO
but with no different results.
Any suggestion?
(Similar question CGContext transparency problem with no answer)
Unless I'm missing something, I believe you get the result you want by setting opaque to NO
I'm pretty sure you can't define a transparency when creating UIImages like this - you could mask your UIImageView which uses the image though.
Something like the following functions allow for this type of operation:
You can than call it like this:
masked_image.png needs to be an alpha channeled image which will cut out your black bg.
i just came across this same problem. what worked for me was assuring that i was working with PNGs and not JPGs, since JPGs do not support alpha channel. hope this works for you.