One way to achieve this is to discolor the image and add a tint on top of that image with the desired color.
Desaturate
-(UIImage *) getImageWithUnsaturatedPixelsOfImage:(UIImage *)image { const int RED = 1, GREEN = 2, BLUE = 3; CGRect imageRect = CGRectMake(0, 0, image.size.width*2, image.size.height*2); int width = imageRect.size.width, height = imageRect.size.height; uint32_t * pixels = (uint32_t *) malloc(width*height*sizeof(uint32_t)); memset(pixels, 0, width * height * sizeof(uint32_t)); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast); CGContextDrawImage(context, CGRectMake(0, 0, width, height), [image CGImage]); for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { uint8_t * rgbaPixel = (uint8_t *) &pixels[y*width+x]; uint32_t gray = (0.3*rgbaPixel[RED]+0.59*rgbaPixel[GREEN]+0.11*rgbaPixel[BLUE]); rgbaPixel[RED] = gray; rgbaPixel[GREEN] = gray; rgbaPixel[BLUE] = gray; } } CGImageRef newImage = CGBitmapContextCreateImage(context); CGContextRelease(context); CGColorSpaceRelease(colorSpace); free(pixels); UIImage * resultUIImage = [UIImage imageWithCGImage:newImage scale:2 orientation:0]; CGImageRelease(newImage); return resultUIImage; }
Overlay with color
-(UIImage *) getImageWithTintedColor:(UIImage *)image withTint:(UIColor *)color withIntensity:(float)alpha { CGSize size = image.size; UIGraphicsBeginImageContextWithOptions(size, FALSE, 2); CGContextRef context = UIGraphicsGetCurrentContext(); [image drawAtPoint:CGPointZero blendMode:kCGBlendModeNormal alpha:1.0]; CGContextSetFillColorWithColor(context, color.CGColor); CGContextSetBlendMode(context, kCGBlendModeOverlay); CGContextSetAlpha(context, alpha); CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(CGPointZero.x, CGPointZero.y, image.size.width, image.size.height)); UIImage * tintedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return tintedImage; }
How-to
You can change the color of the hue as you want.
Fernando Cervantes Mar 30 2018-12-12T00: 00Z
source share