Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying color to gray scale image, preserving alpha values (iOS/Quartz)

This is probably very straightforward, but I am not even sure what it's called - which makes googling a bit less useful than usual.

I have a gray scale line drawing with alpha for anti-aliasing effect. This drawing is used as a player token in a game. Currently, I have created a couple of colorized variants (in Photoshop). But I would like to be able to programmatically tint the original image, while preserving the alpha values. I am using Quartz/Core Graphics, and I suspect that there may be some sort of blend that would accomplish the desired effect - but not sure which or even if that's the right approach.

like image 572
westsider Avatar asked Feb 25 '23 10:02

westsider


1 Answers

Try this.

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 anyway, something very close to that that. Let me know if it works out for you.

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

like image 118
livingtech Avatar answered Feb 27 '23 22:02

livingtech