I'm checking that image have transparent area (alpha) or not. Bashed on that I have to change the color of UIImage
I have implement the below method to check the image have 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;
}
This method is working fine but for some image it is creating issue. See the below image:
For above image alpha return 0;
And for above 2 images alpha have some value.
All 3 images have same white background. For the first image also should have some alpha. it should not be 0. Please guide me out on this ? is there any code error in my method or what?
The alpha channel is a special channel that handles transparency. When an image has an alpha channel on it, it means you can adjust the image's opacity levels and make bits translucent or totally see-through. The alpha channel is instrumental when you want to remove the background from an image.
The alpha channel (also called alpha planes) is a color component that represents the degree of transparency (or opacity) of a color (i.e., the red, green and blue channels). It is used to determine how a pixel is rendered when blended with another.
The absolute simplest way to change colors of images (or icons in this case) is to use the SF Symbols where applicaple. This is a set of symbols Apple provides that can easily be used in your own app. You can download an app to help you find the correct symbol for you needs here.
Rewrite @Hitarth's answer in Swift4:
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With