iPhone - UIImage mask and CopyImageAndAddAlphaChannel function

与世无争的帅哥 提交于 2019-12-11 04:28:33

问题


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


回答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;


来源:https://stackoverflow.com/questions/5111671/iphone-uiimage-mask-and-copyimageandaddalphachannel-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!