手动颜色从一个UIColor褪色到另一个 [英] Manually color fading from one UIColor to another
问题描述
我试图在 drawRect
中将一个 UIColor
淡入另一个。我创建了这个函数来计算一定比例的颜色:
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];
}
这是做每个R / G / B /
What this does is takes each R/G/B/A value and increments it depending on the percentage.
这种工作方式,但不会褪色 [UIColor purpleColor]
到 [UIColor redColor]
。在0.1%时,它显示为绿色而不是紫色,因此它看起来从绿色变为红色,而不是从紫色变为红色。
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.
这篇关于手动颜色从一个UIColor褪色到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!