views:

334

answers:

1

I have a 300 x 400 px PNG-24 with alpha channel. It's about 140kb. I want to mask out some parts of that, so I created another 300 x 400 image as PNG-24 but with only black, gray and white and no alpha channel.

The weird thing is: Where the mask is black, the image is just kept original. No transparency. But where the mask is white, the image gets black just black. No transparency.

It works partially on very small images like 50 x 50 px. Any idea what may be wrong with this function?

+ (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 theImage = image.CGImage;
    CGImageRef masked = CGImageCreateWithMask(theImage, mask);
    return [UIImage imageWithCGImage:masked];
}

My background is orange, so that this color should shine through. The UIImageView that holds the image is set to clearColor / transparency and opaque=NO.

+1  A: 

I guess your code is from here. There is this comment:

I’ve improved the code so that it can correctly mask images that don’t have an alpha channel.

So if it doesn't work for you, perhaps your image doesn't have an alpha channel.

schnaader
Thanks! I figured out my stupid Graphics App will not create an alpha channel if I dont have a transparent pixel, even if I check "Transparent" when saving. That was the problem!
Thanks