我正在尝试UIColor
在drawRect
. 我创建了这个函数来计算一定百分比的颜色:
- (UIColor *)colorFromColor:(UIColor *)fromColor toColor:(UIColor *)toColor percent:(float)percent
{
float dec = percent / 100.f;
CGFloat fRed, fBlue, fGreen, fAlpha;
CGFloat tRed, tBlue, tGreen, tAlpha;
CGFloat red, green, blue, alpha;
if(CGColorGetNumberOfComponents(fromColor.CGColor) == 2) {
[fromColor getWhite:&fRed alpha:&fAlpha];
fGreen = fRed;
fBlue = fRed;
}
else {
[fromColor getRed:&fRed green:&fGreen blue:&fBlue alpha:&fAlpha];
}
if(CGColorGetNumberOfComponents(toColor.CGColor) == 2) {
[toColor getWhite:&tRed alpha:&tAlpha];
tGreen = tRed;
tBlue = tRed;
}
else {
[toColor getRed:&tRed green:&tGreen blue:&tBlue alpha:&tAlpha];
}
red = (dec * (tRed - fRed)) + fRed;
blue = (dec * (tGreen - fGreen)) + fGreen;
green = (dec * (tBlue - fBlue)) + fBlue;
alpha = (dec * (tAlpha - fAlpha)) + fAlpha;
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
这样做是获取每个 R/G/B/A 值并根据百分比增加它。
它有点工作,但不会[UIColor purpleColor]
正确褪色[UIColor redColor]
。在 0.1% 时,它显示为绿色而不是紫色,因此它似乎从绿色变为红色,而不是从紫色变为红色。
有人知道我在做什么错吗?这是计算这个错误的方法吗?有没有更准确的方法来做到这一点?