我有一组黑白图像,如下所示。如果我没记错的话,有某种方法可以设置 UIImage 的混合或遮罩属性以将其与背景 UIView 混合。
在这种情况下,我想将该图像的颜色更改为红色以表示生命值。如何以编程方式更改此 UIImage 的颜色?
我知道图像滤镜的使用,特别是色调偏移,但它们确实是资源密集型的,而且它们不适用于白色图像,所以我正在寻找另一种解决方案。
我尝试用 alpha 0.4 覆盖 UIView 并将其背景颜色设置为红色,结果如下:
This may work in some cases, but in my case I would like to have more control over the shade of color I'm getting.
您可以在此图像的基础上绘制新图像。下面的代码会将图像中的白色与您提供的背景颜色混合。百分比是一个 0-1.0 浮点数,控制从底部开始的图像与您选择的颜色混合的程度,因此可以获得像心形充满红色以代表生命值的结果。
-(UIImage*)blendImage:(UIImage*)image withColor:(UIColor*)color fillUpTo:(float)percent
{
//math got me
float realPercent = 1.0-percent;
CGSize size = image.size;
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, CGRectMake(0, size.height*realPercent, size.width, size.height*(1-realPercent)));
//make sure the image is not upside down
CGContextTranslateCTM(context, 0, image.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
//draw image by blending colors
CGContextSetBlendMode(context, kCGBlendModeMultiply);
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), image.CGImage);
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;
}
结果为 0.3%:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)