我試圖在drawRect
中淡入一個UIColor
到另一個。我已經創建這個功能在一定的百分比來計算顏色:從一個UIColor手動顏色褪色到另一個
- (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%時,它顯示爲綠色而不是紫色,因此它從綠色變爲紅色而不是紫色變爲紅色。
任何人都知道我在做什麼錯了?這是計算這個錯誤的方法嗎?有沒有更準確的方法來做到這一點?
噢,我的!這麼多的紅,綠,藍......我想我已經把他們全都直了!謝謝! – Luke
沒問題。有時你只需要一雙額外的眼睛。 –