Map numeric values to colors in a rainbow in C#

Sometimes it is useful to map values to colors. For example, intensity of color could indicate population density, agricultural yield, rainfall, or other values on a map.

The MapRainbowColor method maps a value between two extremes to a rainbow color. For example, you might want 0 to be represented by red and 100 to be represented by blue. In that case, the extreme values would be 0 and 100.


// Map a value to a rainbow color.
private Color MapRainbowColor(float value, float red_value, float blue_value)
{
// Convert into a value between 0 and 1023.
int int_value = (int)(1023 * (value - red_value) / (blue_value - red_value));

// Map different color bands.
if (int_value < 256)
{
// Red to yellow. (255, 0, 0) to (255, 255, 0).
return Color.FromArgb(255, int_value, 0);
}
else if (int_value < 512)
{
// Yellow to green. (255, 255, 0) to (0, 255, 0).
int_value -= 256;
return Color.FromArgb(255 - int_value, 255, 0);
}
else if (int_value < 768)
{
// Green to aqua. (0, 255, 0) to (0, 255, 255).
int_value -= 512;
return Color.FromArgb(0, 255, int_value);
}
else
{
// Aqua to blue. (0, 255, 255) to (0, 0, 255).
int_value -= 768;
return Color.FromArgb(0, 255 - int_value, 255);
}
}

The code first converts the value into an integer between 0 and 1023. It then determines the part of the rainbow that should hold the color, subtracts an appropriate amount from the integer value to put it within the correct range, and then calculates an appropriate color.

The form's Paint event handler uses the MapRainbowColor method to fill the form with two rainbows. The on on top draws a rainbow shading from red to blue while the one on the bottom shades from blue to red.

// Draw rainbow colors on the form.
private void Form1_Paint(object sender, PaintEventArgs e)
{
int wid = this.ClientSize.Width;
int hgt = this.ClientSize.Height;
int hgt2 = (int)(hgt / 2);
for (int x = 0; x < wid; x++)
{
using (Pen the_pen = new Pen(MapRainbowColor(x, 0, wid)))
{
e.Graphics.DrawLine(the_pen, x, 0, x, hgt2);
}
using (Pen the_pen = new Pen(MapRainbowColor(x, wid, 0)))
{
e.Graphics.DrawLine(the_pen, x, hgt2, x, hgt);
}
}
}

Note that this method is really intended to calculate colors for data values not to fill in large areas as it is used here. The LinearGradientBrush can fill areas with color gradients much more efficiently.

Download example



 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments will be subject to moderation before being displayed.

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.