gpt4 book ai didi

iphone - 如何以编程方式为黑/白 UIImageView 着色?

转载 作者:太空狗 更新时间:2023-10-30 04:00:59 25 4
gpt4 key购买 nike

我有一组黑白图像,如下所示。如果我没记错的话,有一些方法可以设置 UIImage 的混合或 mask 属性以将其与背景 UIView 混合。

在这种情况下,我想将此图像的颜色更改为红色以表示生命值。 如何以编程方式更改此 UIImage 的颜色?

我知道图像过滤器的使用,特别是色调偏移,但它们确实是资源密集型的,而且它们不适用于白色图像,所以我正在寻找另一种解决方案。

Example icon

我尝试用 alpha 0.4 覆盖 UIView 并将其背景颜色设置为红色,结果如下:

enter image description here这在某些情况下可能有效,但在我的情况下,我想更好地控制我得到的颜色阴影。

最佳答案

您可以在此图像的基础上绘制新图像。下面的代码会将图像中的白色与您提供的背景颜色混合。百分比是一个 0-1.0 float ,用于控制从底部开始的图像中有多少与您选择的颜色混合,因此可以获得像心脏充满红色以表示生命值的结果。

-(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% 的结果:

enter image description here

关于iphone - 如何以编程方式为黑/白 UIImageView 着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20673209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com