Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>Something like the following functions allow for this type of operation:</p> <pre><code>// handles img masking operation CGImageRef CopyImageAndAddAlphaChannel(CGImageRef sourceImage) { CGImageRef retVal = NULL; size_t width = CGImageGetWidth(sourceImage); size_t height = CGImageGetHeight(sourceImage); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef offscreenContext = CGBitmapContextCreate(NULL, width, height, 8, 0, colorSpace, kCGImageAlphaPremultipliedFirst); if (offscreenContext != NULL) { CGContextDrawImage(offscreenContext, CGRectMake(0, 0, width, height), sourceImage); retVal = CGBitmapContextCreateImage(offscreenContext); CGContextRelease(offscreenContext); } CGColorSpaceRelease(colorSpace); return retVal; } // png masks can mask png, gif or jpg... - (UIImage*)maskImage:(UIImage *)image withMask:(UIImage *)maskImage { CGImageRef maskRef = maskImage.CGImage; CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef), CGImageGetHeight(maskRef), CGImageGetBitsPerComponent(maskRef), CGImageGetBitsPerPixel(maskRef), CGImageGetBytesPerRow(maskRef), CGImageGetDataProvider(maskRef), NULL, false); CGImageRef sourceImage = [image CGImage]; CGImageRef imageWithAlpha = sourceImage; //add alpha channel for images that don't have one (ie GIF, JPEG, etc...) //this however has a computational cost if ((CGImageGetAlphaInfo(sourceImage) == kCGImageAlphaNone) || (CGImageGetAlphaInfo(sourceImage) == kCGImageAlphaNoneSkipFirst)) { imageWithAlpha = CopyImageAndAddAlphaChannel(sourceImage); } CGImageRef masked = CGImageCreateWithMask(imageWithAlpha, mask); CGImageRelease(mask); //release imageWithAlpha if it was created by CopyImageAndAddAlphaChannel if (sourceImage != imageWithAlpha) { CGImageRelease(imageWithAlpha); } UIImage* retImage = [UIImage imageWithCGImage:masked]; CGImageRelease(masked); return retImage; } </code></pre> <p>You can than call it like this:</p> <pre><code>UIImage *imgMasked = [self maskImage:[UIImage imageNamed:@"full_image.png"] withMask:[UIImage imageNamed:@"masked_image.png"]]; </code></pre> <p>masked_image.png needs to be an alpha channeled image which will cut out your black bg.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload