iOS color to transparent in UIImage

UIImage *image = [UIImage imageNamed:@"image.png"];

const float colorMasking[6] = {1.0, 1.0, 0.0, 0.0, 1.0, 1.0};
image = [UIImage imageWithCGImage: CGImageCreateWithMaskingColors(image.CGImage, colorMasking)];

You receive nil, because parameters, that you send is invalid. If you open Apple documentation, you will see this:

Components
An array of color components that specify a color or range of colors to mask the image with. The array must contain 2N values { min[1], max[1], ... min[N], max[N] } where N is the number of components in color space of image. Each value in components must be a valid image sample value. If image has integer pixel components, then each value must be in the range [0 .. 2**bitsPerComponent - 1] (where bitsPerComponent is the number of bits/component of image). If image has floating-point pixel components, then each value may be any floating-point number which is a valid color component.

You can quickly open documentation by holding Option + Mouse Click on some function or class, like CGImageCreateWithMaskingColors.


I made this static function that removes the white background you can use it replacing the mask with the color range you want to remove:

+ (UIImage*) processImage :(UIImage*) image
{
    const float colorMasking[6]={222,255,222,255,222,255};
    CGImageRef imageRef = CGImageCreateWithMaskingColors(image.CGImage, colorMasking);
    UIImage* imageB = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return imageB;
}

Tags:

Ios

Uiimage