开发者

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

开发者 https://www.devze.com 2023-02-03 13:24 出处:网络
This is probably very straightforward, but I am not even sure what it\'s called - which makes goog开发者_开发技巧ling a bit less useful than usual.

This is probably very straightforward, but I am not even sure what it's called - which makes goog开发者_开发技巧ling 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消