我正在尝试在运行时更改图像的颜色。我在SO上看到了几个答案,但它们都改变了背景颜色而不是前景,这正是我想要做的。我的代码基于另一个SO thread。
这是我的代码:
@implementation UIImage (Coloring)
-(UIImage*) imageWithColorOverlay:(UIColor*)color
{
//create context
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
CGContextRef context = UIGraphicsGetCurrentContext();
// drawingcode
//bg
CGRect rect = CGRectMake(0.0, 0.0, self.size.width, self.size.height);
[self drawInRect:rect];
//fg
CGContextSetBlendMode(context, kCGBlendModeMultiply);
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//end
return image;
}
@end
这是迄今为止的结果:
从左到右:
UIView
,图像的bg是透明的。kCGBlendModeMultiply
kCGBlendModeColorBurn
是否有CGBlendMode
可以替换前景色?此外,是否可以替换前景色(白色)和阴影(黑色)?
答案 0 :(得分:3)
在搞乱了不同的混合选项后,这段代码就行了。唯一需要注意的是,红色色调显示在阴影中,它在技术上并不正确,但它的关闭性很强
@implementation UIImage (Coloring)
-(UIImage*) imageWithColorOverlay:(UIColor*)color
{
//create context
UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
CGContextRef context = UIGraphicsGetCurrentContext();
//drawingcode
//bg
CGRect rect = CGRectMake(0.0, 0.0, self.size.width, self.size.height);
[self drawInRect:rect];
//fg
CGContextSetBlendMode(context, kCGBlendModeMultiply);
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);
//mask
[self drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0];
//end
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}