views:

647

answers:

3

I'd like to have an enumeration of Colors based on the rainbow colors (red... yellow... green... blue...).

I see basically two ways to do that:

  1. Create a lookup table containing some important reference colors and interpolate between these. I don't like this idea at all.

  2. Apply some more or less fancy math. Probably less, but I don't quite see how it works. Any ideas?

(Oh, and while I did some SO research, I found no good results. If this question was already posted, please just point me to the location and I'll delete this.)

Edit: I'd prefer to have this independent of the used technology to display the gradient. For instance, something like GetRainbowColor (float f) with f ranging from 0 (red) to 1 (violet) would work great.

A: 

Start here: http://www.midnightkite.com/color.html

You can interpret this: http://www.physics.sfasu.edu/astro/color/spectra.html it's FORTRAN, but it's pretty obvious what it does.

Also, you can read more in-depth here: http://en.wikipedia.org/wiki/CIE_1931_color_space

Here's a version in Python: http://www.johnny-lin.com/py_code/wavelen2rgb.py

BTW, the first google hit for C# is this: http://miguelmoreno.net/sandbox/wavelengthtoRGB/default.aspx

S.Lott
+1  A: 

In winforms(or anything using GDI+) you could use System.Drawing.Drawing2D.LinearGradientBrush to do the interpolation for you.

WPF's System.Windows.Media.GradientBrush could work as well. It's abstract so you might end up with WPF's LinearGradientBrush. It's in a different namespace than the other.

EDIT: since the question was edited to indicate that you want to be tech independent I don't think this answer applies. I'm going to leave it here for now incase someone is looking for Gradients in C#, but if someone finds that objectionable I'll remove the answer.

I did a quick check to see if you could at least get at some of the funtionality in a more independent way (such as getting an array of Point or something). Doesn't appear to be the case.

Mike Two
+11  A: 

This is easier than you think.

First you need an hsv or hsl to rgb conversion function. Here is C# code to do that conversion.

Then you simply iterate over all of the possible values of the hue h while keeping the saturation s and luminosity l constant.

If you want 100 colors of the rainbow spaced out equally:

for(double i = 0; i < 1; i+=0.01)
{
    ColorRGB c = HSL2RGB(i, 0.5, 0.5);
    //do something with the color
}

You could also easily create your desired function GetRainbowColor this way by adding all of these colors to a List<ColorRGB> and returning the appropriate indexed color.

Brian R. Bondy
See also http://en.wikipedia.org/wiki/HLS_color_space , there is a section about converting HSL to/from RGB
DNNX