I am trying to generate the below Color Gradient ( the Color is blue at one end, and red at the other).
(source: brothersoft.com )
I follow the suggestion put forth here . This is my code:
int rMax = Color.Red.R;
int rMin = Color.Blue.R;
// ... and for B, G
var colorList = new List<Color>();
for(int i=0; i<size; i++)
{
var rAverage = rMin + (int)((rMax - rMin) * i / size);
// ... and for B, G
colorList.Add(Color.FromArgb(rAverage, gAverage, bAverage));
}
Although the result I did show a gradual, smooth transition from Red to Blue, but other intermediate color such as yellow and green didn't show up at all.
Anything I did wrong?
You should work with colors in the HSL color space, not RGB. That allows you to smoothly change the hue value from 0 (red) to 1 (violet). The System.Drawing.Color structure allows converting from RBG to HSL (GetHue etc) but not the other way. The math is simple though .
int rMax = Color.Red.R;
int rMin = Color.Blue.R;
// ... and for B, G
var colorList = new List<Color>();
for(int i=0; i<size; i++)
{
var rAverage = rMin + (int)((rMax - rMin) * i / size);
// ... and for B, G
colorList.Add(Color.FromArgb(rAverage, gAverage, bAverage));
}
You are setting rMin = 0
and rMax = 255
. Thus you are essentially setting
rAverage = 255 * i / size;
You don't have the code for gAverage
and bAverage
listed, but if it were truly equivalent you'd be seeing a gradual trasition from black->gray->white, with no other hues at all.
It seems likely that what you want is to iterate over the different hues at a constant lightness/saturation. See here for an example C# class which does that, and here for an explanation of the equation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.