这可能非常简单,但我什至不确定它叫什么 - 这使得谷歌搜索不如平时有用。
我有一个带有 alpha 的灰度线条图,用于抗锯齿效果。该绘图在游戏中用作玩家标记。目前,我已经创建了几个彩色变体(在 Photoshop 中)。但我希望能够以编程方式对原始图像进行着色,同时保留 alpha 值。我正在使用 Quartz/Core Graphics,我怀疑可能有某种混合可以达到预期的效果 - 但不确定哪种方法甚至是否是正确的方法。
最佳答案
试试这个。
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);
}
然后,使用它:
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]];
...或者无论如何,非常接近那个。让我知道它是否适合您。
您还可以使用 CGContextSetBlendMode()
的第二个参数来获得略有不同的效果。
关于iphone - 将颜色应用于灰度图像,保留 alpha 值 (iOS/Quartz),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4663323/