Image mask problem

Discussion in 'iOS Programming' started by mrl72, Jan 29, 2011.

  1. mrl72 macrumors regular

    Apr 20, 2008
    I've been using the same code to apply an image mask (non alpha channel PNG) to the image on a button without any problems. I've been doing this real-time but have recently decided to cache the image with the mask applied before I add it to the button. I have changed nothing except instead of applying the mask before it's added to the button, I write it to file and then use the cached version of the image on the button. No code changes to the mask process at all, which is as follows:

    - (UIImage*) maskImage:(UIImage *)image large:(BOOL)largeImage {
    	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    	UIImage *maskImage;
    	if (largeImage) {
    		maskImage = [UIImage imageNamed:@"imagemask_large.png"];
    	} else {
    		maskImage = [UIImage imageNamed:@"imagemask.png"];
    	CGImageRef maskImageRef = [maskImage CGImage];
    	// create a bitmap graphics context the size of the image
    	CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    	if (mainViewContentContext==NULL)
    		return NULL;
    	CGFloat ratio = 0;
    	ratio = maskImage.size.width/ image.size.width;
    	if(ratio * image.size.height < maskImage.size.height) {
    		ratio = maskImage.size.height/ image.size.height;
    	CGRect rect1  = {{0, 0}, {maskImage.size.width, maskImage.size.height}};
    	CGRect rect2  = {{-((image.size.width*ratio)-maskImage.size.width)/2 , -((image.size.height*ratio)-maskImage.size.height)/2}, {image.size.width*ratio, image.size.height*ratio}};
    	CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
    	CGContextDrawImage(mainViewContentContext, rect2, image.CGImage);
    	// Create CGImageRef of the main view bitmap content, and then
    	// release that bitmap context
    	CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
    	UIImage *theImage = [UIImage imageWithCGImage:newImage];
    	// return the image
    	return theImage;
    Yet by doing this my images which were once perfect now have a weird transparency mask. Is it becuase the only difference is I'm writing the "masked" version out with UIImageJPEGRepresentation perhaps? Any ideas what's going wrong?

    Example result before with setting the mask at run time and then applying to button (correct result - note the corners are black but they actually appear transparent when applied to the button):


    Example after written to disk instead of applied to the button:

  2. chown33 macrumors 604

    Aug 9, 2009
    Sailing beyond the sunset

Share This Page