为什么我的图像遮罩使图像变黑,而遮罩是白色的?
我有一个带有 alpha 通道的 300 x 400 px PNG-24。 大约140kb。 我想遮盖其中的某些部分,因此我创建了另一个 300 x 400 图像作为 PNG-24,但只有黑色、灰色和白色,没有 Alpha 通道。
奇怪的是:如果蒙版是黑色的,图像就保持原始状态。 没有透明度。 但如果蒙版是白色的,图像就会变成黑色。 没有透明度。
它部分适用于非常小的图像,例如 50 x 50 像素。 知道这个函数可能有什么问题吗?
+ (UIImage*)maskImage:(UIImage*)image withMask:(UIImage*)maskImage {
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef),
NULL, false);
CGImageRef theImage = image.CGImage;
CGImageRef masked = CGImageCreateWithMask(theImage, mask);
return [UIImage imageWithCGImage:masked];
}
我的背景是橙色的,所以这种颜色应该会发光。 保存图像的UIImageView设置为clearColor/透明度和opaque=NO。
I have a 300 x 400 px PNG-24 with alpha channel. It's about 140kb. I want to mask out some parts of that, so I created another 300 x 400 image as PNG-24 but with only black, gray and white and no alpha channel.
The weird thing is: Where the mask is black, the image is just kept original. No transparency. But where the mask is white, the image gets black just black. No transparency.
It works partially on very small images like 50 x 50 px. Any idea what may be wrong with this function?
+ (UIImage*)maskImage:(UIImage*)image withMask:(UIImage*)maskImage {
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef),
NULL, false);
CGImageRef theImage = image.CGImage;
CGImageRef masked = CGImageCreateWithMask(theImage, mask);
return [UIImage imageWithCGImage:masked];
}
My background is orange, so that this color should shine through. The UIImageView that holds the image is set to clearColor / transparency and opaque=NO.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜你的代码是来自这里。 有这样一条评论:
因此,如果它不适合您,则可能您的图像没有 Alpha 通道。
I guess your code is from here. There is this comment:
So if it doesn't work for you, perhaps your image doesn't have an alpha channel.
小心 - 代码会泄漏! 直到循环运行这个方法我才注意到它。 确保在返回图像之前调用
CGImageRelease(mask)
和CGImageRelease(masked)
。Be careful - that code leaks! I didn't notice it until running this method in a loop. Make sure to call
CGImageRelease(mask)
andCGImageRelease(masked)
before returning the image.