views:

504

answers:

2

I am trying to generate the below Color Gradient ( the Color is blue at one end, and red at the other).

alt text

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?

+1  A: 
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.

BlueRaja - Danny Pflughoeft
+3  A: 

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.

Hans Passant
Check out http://www.bobpowell.net/rgbhsb.htm for .NET RGB / HSL conversion code
AakashM
...That is exactly what I said.
BlueRaja - Danny Pflughoeft