我正在检查图像是否有透明区域(alpha)。受到打击,我必须改变颜色UIImage
我已经实现了以下方法来检查图像是否有alpha
or not.
- (BOOL) checkAlpha : (UIImage*) image
{
for(int x = 0; x < image.size.width ; x++)
{
for(int y = 0; y < image.size. height; y++)
{
CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
const UInt8* data = CFDataGetBytePtr(pixelData);
int pixelInfo = ((image.size.width * y) + x ) * 4; // The image is png
UInt8 red = data[pixelInfo]; // If you need this info, enable it
UInt8 green = data[(pixelInfo + 1)]; // If you need this info, enable it
UInt8 blue = data[pixelInfo + 2]; // If you need this info, enable it
UInt8 alpha = data[pixelInfo + 3]; // I need only this info for my maze game
CFRelease(pixelData);
UIColor* color = [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha/255.0f];
DLog(@"color : %@",color);
DLog(@"alpha : %hhu",alpha)
if (alpha)
return YES; // display original image from url.
else
return NO; // apply brand color here.
}
}
return YES;
}
这种方法工作正常,但对于某些图像来说它会产生问题。
见下图:
For above image alpha return 0;
And for above 2 images alpha have some value.
所有 3 个图像都有相同的白色背景。
对于第一张图像也应该有一些 Alpha。它不应该是0。
请指导我解决这个问题?我的方法有代码错误还是什么?
在 Swift4 中重写 @Hitarth 的答案:
extension UIImage {
public func isTransparent() -> Bool {
guard let alpha: CGImageAlphaInfo = self.cgImage?.alphaInfo else { return false }
return alpha == .first || alpha == .last || alpha == .premultipliedFirst || alpha == .premultipliedLast
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)