How do I get a rainbow color gradient in C#?

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.

Leave a Comment