iphone - 将颜色应用于灰度图像,保留 alpha 值 (iOS/Quartz)

标签 iphone ios core-graphics quartz-graphics alphablending

这可能非常简单,但我什至不确定它叫什么 - 这使得谷歌搜索不如平时有用。

我有一个带有 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/

相关文章:

java - AES256加密 objective-c 实现

iphone - 在线编译 XCode 项目

ios - 球体上两点之间的圆柱方向,Scenekit,四元数 IOS

core-graphics - 合并核心图形中的路径?

ios - 在 func draw() 下的 UIBezier 路径的动画 CGAffineTransform(rotate)

iphone - iPhone/iPad 中 Chrome 浏览器的 WebRTC 支持

ios - 旋转后键盘延伸高度不正确

ios - Swift Real - 如何将数据附加到在不同类中创建的对象

ios - 如何使用 Home Kit 配件模拟器

iphone - CGContextDrawImage 是否即时解压缩 PNG?