I'm trying to fade one UIColor
to another in a drawRect
. I've created this function to calculate a color at a certain percentage:
- (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];
}
What this does is takes each R/G/B/A value and increments it depending on the percentage.
It kind of works, but doesn't fade [UIColor purpleColor]
to [UIColor redColor]
correctly. At 0.1 percent it shows up as a green color rather than purple, so it appears to fade from green to red instead of purple to red.
Anyone know what I'm doing wrong? Is this the wrong approach to calculating this? Is there a more accurate way to do this?
You've got your green and blue swapped on the last few lines.
Updated version for swift