Iphone - 屏蔽JPG图像

时间:2011-02-23 10:38:31

标签: iphone uiimage jpeg mask

我正在编写一个拼图游戏,我需要屏蔽图像以创建拼图。

我正在使用在线服务器上的图片,它们是* .JPG。当我屏蔽它们时,应该是透明的区域是黑色的。

我可以通过编程方式添加Alpha通道吗?如果是的话,你能告诉我怎么做吗?

非常感谢, 安德烈

1 个答案:

答案 0 :(得分:4)

我找到了答案:

CGImageRef imageRef = self.CGImage;
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);

// The bitsPerComponent and bitmapInfo values are hard-coded to prevent an "unsupported parameter combination" error
CGContextRef offscreenContext = CGBitmapContextCreate(NULL,
                                                      width,
                                                      height,
                                                      8,
                                                      0,
                                                      CGImageGetColorSpace(imageRef),
                                                      kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);

// Draw the image into the context and retrieve the new image, which will now have an alpha layer
CGContextDrawImage(offscreenContext, CGRectMake(0, 0, width, height), imageRef);
CGImageRef imageRefWithAlpha = CGBitmapContextCreateImage(offscreenContext);
UIImage *imageWithAlpha = [UIImage imageWithCGImage:imageRefWithAlpha];

// Clean up
CGContextRelease(offscreenContext);
CGImageRelease(imageRefWithAlpha);

return imageWithAlpha;