I have an image with white border and black color filled inside it. I want to just change the black color to another color at runtime. The user will select the color at runtime in HSB format. How can I do that? I tried CGImageCreateWithMaskingColors by taking const float colorMasking[4]={255, 255, 255, 255}; but I am getting a nil CGImageRef everytime. Please help.
- (UIImage*) maskBlackInImage :(UIImage*) image color:(UIColor*)color
{
const CGFloat colorMasking[4] = { 222, 255, 222, 255 };
CGImageRef imageRef = CGImageCreateWithMaskingColors(image.CGImage, colorMasking);
UIImage* imageB = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return imageB;
}
I am attaching the image of bulb - Bulb with Black color filled, white border and transparent background
Update:
I was able to fill black color with another color after using the code in the accepted answer. But, I could see a little bit of color on white border. The image doesn't look that sharp. Attaching the output:
Create a category of UIImage
class and add the following method
- (UIImage *)imageTintedWithColor:(UIColor *)color
{
UIImage *image;
if (color) {
// Construct new image the same size as this one.
UIGraphicsBeginImageContextWithOptions([self size], NO, 0.0); // 0.0 for scale means "scale for device's main screen".
CGRect rect = CGRectZero;
rect.size = [self size];
// tint the image
[self drawInRect:rect];
[color set];
UIRectFillUsingBlendMode(rect, kCGBlendModeScreen);
// restore alpha channel
[self drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0f];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return image;
}