1

I am trying to create a jigsaw puzzle and I need to mask the UIImages to obtain the puzzle pieces.

I don't understand how can I mask a JPG picture because as I understand it doesn't have an alpha channel. Can anyone help me with this? The JPGs are on an online server and there is no way to download them as PNG.

And one more thing, I can’t find this function anywhere on the Apple documentation: “CopyImageAndAddAlphaChannel”. Does it even exist. I found a few references on some forums but nothing strait forward.

Thanks a lot, Andrei

Andrei Neacsu
  • 1,453
  • 3
  • 20
  • 33

1 Answers1

1

Found the answer. Here is the function, it works for JPG and PNG without alpha channel (I have tested it :)):

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


CGContextRef offscreenContext = CGBitmapContextCreate(NULL,
                                                      width,
                                                      height,
                                                      8,
                                                      0,
                                                      CGImageGetColorSpace(imageRef),
                                                      kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);


CGContextDrawImage(offscreenContext, CGRectMake(0, 0, width, height), imageRef);
CGImageRef imageRefWithAlpha = CGBitmapContextCreateImage(offscreenContext);
UIImage *imageWithAlpha = [UIImage imageWithCGImage:imageRefWithAlpha];


CGContextRelease(offscreenContext);
CGImageRelease(imageRefWithAlpha);

return imageWithAlpha;
Andrei Neacsu
  • 1,453
  • 3
  • 20
  • 33
  • Thanks for sharing the code, but does this just add a blank alpha channel? Looking for something that will take separate image and an alpha and combine them. Maybe I need to look at CGImageMaskCreate? – ayreguitar Jun 08 '12 at 08:14