我正在尝试在运行时更改图像的颜色。我已经看到了几个关于 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
这是迄今为止的结果:
从左到右:
- 没有混合,只是普通资源。灰色背景来自imageviews后面的
UIView
,图像的背景是透明的。 - 与
kCGBlendModeMultiply
相乘 - 使用
kCGBlendModeColorBurn
进行颜色加深
是否有一个CGBlendMode
可以实现替换前景色?另外,是否可以同时替换前景色(白色)和阴影(黑色)?
最佳答案
在尝试了不同的混合选项之后,这段代码成功了。唯一需要注意的是,红色色调显示在阴影中,这在技术上不正确,但很接近
@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;
}
关于ios - 使用混合对图像着色/遮蔽前景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18006520/