您可以在此圖像上繪製新的圖像庫。下面的代碼會將圖像中的白色與您提供的背景顏色混合。百分比是一個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%:
![enter image description here](https://i.stack.imgur.com/ffIZX.png)
我試過這個,這個想法聽起來非常好,但結果增加了黑色區域的顏色。我添加了結果的示例圖像。 –