开发者

UIImage with mask/alpha weirdness

I'm experiencing some weirdness with a UIImage. Basically, I'm:

  • Loading an image from the Photo album into a UIImage.
  • Creating a mask that consists of an black ellipse over white开发者_运维技巧.
  • Using CGImageCreateWithMask to cut out a portion of the original UIImage.
  • Display the resulting UIImage onscreen and it looks correct.
  • Save out the same UIImage into a PNG.

But when I look at the resulting PNG file, the alpha is reversed!

Any ideas out there?

Here's the code:

// originalImage is the UIImage loaded from the photo album

CGImageRef cgImage = [originalImage CGImage];

// make sure that this has an alpha channel    
CGImageRef shrunk1 = CopyImageAndAddAlphaChannel(shrunk);

// create oval mask
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGContextRef oc = CGBitmapContextCreate(NULL, desiredWidth, desiredHeight,
                                                8,
                                                desiredWidth * 4,
                                                colorspace,
                                                kCGImageAlphaNoneSkipLast);
// over white bgd
CGContextSetRGBFillColor(oc, 1.0, 1.0, 1.0, 1.0);
CGContextFillRect(oc, CGRectMake(0, 0, desiredWidth, desiredHeight));

// black oval
CGContextSetRGBFillColor(oc, 0.0, 0.0, 0.0, 1.0);
CGContextFillEllipseInRect(oc, CGRectMake(0, 0, desiredWidth, desiredHeight));
CGImageRef mask1 = CGBitmapContextCreateImage(oc);

CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(mask1), CGImageGetHeight(mask1),     CGImageGetBitsPerComponent(mask1), CGImageGetBitsPerPixel(mask1), CGImageGetBytesPerRow(mask1), CGImageGetDataProvider(mask1), NULL, NULL);

// cut out the original image with the oval mask
CGImageRef shrunk2 = CGImageCreateWithMask(shrunk1, mask);

// save it
UIImage *final = [UIImage imageWithCGImage:shrunk2];
NSString *s = [self getDateTimeFilename];
NSString *pngPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@.png", s];
[UIImagePNGRepresentation(final) writeToFile:pngPath atomically:YES];

CGImageRelease(shrunk2);
CGImageRelease(mask);
CGImageRelease(mask1);
CGContextRelease(oc);
CGColorSpaceRelease(colorspace);

Any and all help would be greatly appreciated. Thanks!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜