I'm trying to fade a color, let's say Yellow
to White
over a period of time. I've got the timer worked out, and I'm applying the new color just fine as well, but the fade isn't smooth (e.g. it fades into some weird colors before it gets to White
, some of which are darker than their predecessor on the "fade chain" let's call it). I'm confident that's because the math is wrong, but I just can't seem to find a good example of the math for me to modify what I'm doing.
I even pulled the basics of the ColorCeiling
code from this question: Fade a color to white (increasing brightness)
Right now I take a color, and call an extension method Increase
:
dataGridViewResults.Rows[0].DefaultCellStyle.BackColor.Increase(50);
public static Color Increase(this Color color, byte offset)
{
return Color.FromArgb(
color.A.ColorCeiling(offset),
color.R.ColorCeiling(offset),
color.G.ColorCeiling(offset),
color.B.ColorCeiling(offset));
}
and as you can see, each color is then modified by an offset with a ceiling in mind to keep exceptions from being thrown. That extension method, ColorCeiling
looks like this:
public static int ColorCeiling(this byte val, byte modifier, byte ceiling = 255)
{
return (val + modifier > ceiling) ? ceiling : val + modifier;
}
Now, I'm confident that ColorCeiling
is the problem, but I honestly just can't find the math. I honestly feel like just incrementing the ARGB is almost certainly the wrong approach, it seems like you'd say I want you to be 50% lighter, but I just don't know what that means as far as code.
Here's an idea that might work.
Don't do the math in Red-Green-Blue space. Instead treat your colour as having three components:
There are algorithms for converting from RGB to HSV; look them up. This is a good place to start:
http://en.wikipedia.org/wiki/HSL_and_HSV
Now when you are fading from one color to the other, take steps along the HSV axes, not along the RGB axes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With