我试图在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%时,它显示为绿色而不是紫色,因此它看起来从绿色变为红色而不是从紫色变为红色.
解决方法
在最后几行你已经换了绿色和蓝色.