Applying a color image to a gray scale, saving alpha values ​​(iOS / Quartz)

This is probably very simple, but I'm not even sure what he called - which makes googling a little less useful than usual.

I have a rough line with alpha for the smoothing effect. This graphic is used as the player’s token in the game. Currently, I have created a couple of color options (in Photoshop). But I would like to be able to programmatically tint the original image while preserving the alpha values. I use quartz / basic graphics, and I suspect that there may be some kind of mixture that would achieve the desired effect - but I'm not sure which or even if this is the right approach.

+4
source share
1 answer

Try it.

ColorChangingImageView.h

#import <UIKit/UIKit.h> @interface ColorChangingImageView : UIView @property (strong, nonatomic) UIImage *image; @property (strong, nonatomic) UIColor *colorToChangeInto; @end 

ColorChangingImageView.m

 #import "ColorChangingImageView.h" @implementation ColorChangingImageView @synthesize image = _image; @synthesize colorToChangeInto = _colorToChangeInto; - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextScaleCTM(context, 1, -1); CGContextTranslateCTM(context, 0, -rect.size.height); CGImageRef maskImage = [self.image CGImage]; CGContextClipToMask(context, rect, maskImage); [_colorToChangeInto setFill]; CGContextFillRect(context, rect); //blend mode overlay CGContextSetBlendMode(context, kCGBlendModeOverlay); //draw the image CGContextDrawImage(context, rect, _image.CGImage); } 

Then, to use it:

 ColorChangingImageView *iv = [[ColorChangingImageView alloc] initWithFrame:rect]; [iv setBackgroundColor:[UIColor clearColor]]; // might not need this, not sure. [iv setImage:[UIImage imageNamed:@"image.png"]]; [iv setColorToChangeInto:[UIColor blueColor]]; 

... or at least something very close to that. Let me know if this works for you.

You can also play with the second parameter CGContextSetBlendMode() for slightly different effects.

+8
source

Source: https://habr.com/ru/post/1335169/


All Articles