[英]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. 我有一个带有alpha的灰度线条图,用于消除锯齿效果。 This drawing is used as a player token in a game. 该图用作游戏中的玩家令牌。 Currently, I have created a couple of colorized variants (in Photoshop). 目前,我已经创建了几个彩色变体(在Photoshop中)。 But I would like to be able to programmatically tint the original image, while preserving the alpha values. 但我希望能够以编程方式为原始图像着色,同时保留alpha值。 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. 我正在使用Quartz / Core Graphics,我怀疑可能会有某种混合方式可以达到预期的效果 - 但不确定哪种方式,甚至不确定方法是否合适。
Try this. 试试这个。
ColorChangingImageView.h : ColorChangingImageView.h :
#import <UIKit/UIKit.h>
@interface ColorChangingImageView : UIView
@property (strong, nonatomic) UIImage *image;
@property (strong, nonatomic) UIColor *colorToChangeInto;
@end
ColorChangingImageView.m : 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. 您还可以使用CGContextSetBlendMode()
的第二个参数来获得稍微不同的效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.