Skip to content

Instantly share code, notes, and snippets.

@cxjwin
Created April 22, 2019 02:59
Show Gist options
  • Save cxjwin/765c7697695e7854eea4e027eea9ff8f to your computer and use it in GitHub Desktop.
Save cxjwin/765c7697695e7854eea4e027eea9ff8f to your computer and use it in GitHub Desktop.
UIImage with tint color
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIImage (TintColor)
- (UIImage *)imageWithOriginalImage:(UIImage *)image
tintColor:(UIColor *)tintColor;
@end
NS_ASSUME_NONNULL_END
#import "UIImage+TintColor.h"
@implementation UIImage (TintColor)
- (UIImage *)imageWithOriginalImage:(UIImage *)image
tintColor:(UIColor *)tintColor {
#define CASE_1 1
#if CASE_1 == 1
CIImage *ciImage = [[CIImage alloc] initWithImage:image];
CIFilter *filter = [CIFilter filterWithName:@"CIMultiplyCompositing"];
// set color
CIFilter *colorFilter = [CIFilter filterWithName:@"CIConstantColorGenerator"];
CIColor *ciColor = [[CIColor alloc] initWithColor:tintColor];
[colorFilter setValue:ciColor forKey:kCIInputColorKey];
CIImage *colorImage = colorFilter.outputImage;
[filter setValue:colorImage forKey:kCIInputImageKey];
[filter setValue:ciImage forKey:kCIInputBackgroundImageKey];
// output image
UIImage *outputImage = [UIImage imageWithCIImage:filter.outputImage scale:image.scale orientation:image.imageOrientation];
outputImage = [outputImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
return outputImage;
#else
CIImage *ciImage = [[CIImage alloc] initWithImage:image];
CIFilter *filter = [CIFilter filterWithName:@"CIColorMatrix"];
[filter setValue:ciImage forKey:kCIInputImageKey];
// set color
CGFloat r, g, b, a;
[tintColor getRed:&r green:&g blue:&b alpha:&a];
CIVector *rVector = [CIVector vectorWithX:r Y:0 Z:0 W:0];
CIVector *gVector = [CIVector vectorWithX:0 Y:g Z:0 W:0];
CIVector *bVector = [CIVector vectorWithX:0 Y:0 Z:b W:0];
CIVector *aVector = [CIVector vectorWithX:0 Y:0 Z:0 W:a];
[filter setValue:rVector forKey:@"inputRVector"];
[filter setValue:gVector forKey:@"inputGVector"];
[filter setValue:bVector forKey:@"inputBVector"];
[filter setValue:aVector forKey:@"inputAVector"];
// output image
UIImage *outputImage = [UIImage imageWithCIImage:filter.outputImage
scale:image.scale
orientation:image.imageOrientation];
outputImage = [outputImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
return outputImage;
#endif
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment