解决方案:利用BlendMode修改图像,我们将用blending给这张图片加上另一个纯色作为tint,并保持原来的alpha通道。用Core Graphics实现:
创建一个上下文用以画新的图片
将新的tintColor设置为填充颜色
将原图片画在创建的上下文中,并用新的填充色着色(注意保持alpha通道)
从当前上下文中取得图片并返回。
最麻烦的部分可能就是保持alpha通道了。UIImage的文档中提供了使用blend绘图的方法drawInRect:blendMode:alpha:,rect和alpha都没什么问题,但是blendMode是个啥玩意儿啊…继续看文档,关于CGBlendMode的文档,里面有一大堆看不懂的枚举值,比如这样:
The blend mode constants introduced in OS X v10.5 represent the Porter-Duff blend modes.
The symbols in the equations for these blend modes are:
R is the premultiplied result
S is the source color, and includes alpha
D is the destination color, and includes alpha
Ra, Sa, and Da are the alpha components of R, S, and D
R表示结果,S表示包含alpha的原色,D表示包含alpha的目标色,Ra,Sa和Da分别是三个的alpha。
kCGBlendModeDestinationIn 模式解释:结果 = 目标色和原色透明度的加成
R = D*Sa
AvailableiniOS2.0andlater.
DeclaredinCGContext.h.
在UIImage分类中添加以下方法:
- (UIImage*)imageChangeTintColor:(UIColor*)tintColor {
//We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
[tintColor setFill];
CGRect bounds = CGRectMake(0 ,0 , self.size.width, self.size.height);
UIRectFill(bounds);
//Draw the tinted image in context
[self drawInRect:bounds blendMode:kCGBlendModeLuminosity alpha:1.0f];
//kCGBlendModeDestinationIn R = D*Sa Available in iOS 2.0 and later. Declared in CGContext.h.
[self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return tintedImage;
}