Converting int value to a color in a gradient

I have an int value that can range from -148 to 10 and I'm trying to map this value to a color in the following gradient:

  • Black (-148)
  • Blue
  • Cyan
  • Green
  • Yellow
  • Orange
  • Red
  • White (10)

Visually, my color gradient looks like this:

My first thought was to break the range (-148 to 10) down into smaller groups that correspond to these eight colors but that obviously results in multiple values translating into the same color. I'd like to make use of many more or even all the colors in this gradient but I'm not sure how to go about doing this. Can anyone offer some advice? For what it's worth, I'm working in C#/.NET so I need to translate my int into RGB values.


Did you mean a mapping function like this? (The Transparent entry in the colors list is a dummy in the case of value 10 where color1 is taken from the 9th entry of the list)

    Color[] colors = new Color[] { Colors.Black, Colors.Blue, Colors.Cyan, Colors.Green, Colors.Yellow, Colors.Orange, Colors.Red, Colors.White, Colors.Transparent };
    public Color IntToColor(int i)
        float scaled = (float)(i + 148) / 158 * 7;
        Color color0 = colors[(int)scaled];
        Color color1 = colors[(int)scaled + 1];
        float fraction = scaled - (int)scaled;
        Color result = new Color();
        result.R = (byte)((1 - fraction) * (float)color0.R + fraction * (float)color1.R);
        result.G = (byte)((1 - fraction) * (float)color0.G + fraction * (float)color1.G);
        result.B = (byte)((1 - fraction) * (float)color0.B + fraction * (float)color1.B);
        result.A = 255;
        return result;

P.S.: For simplicity there is no check for the [-148:10] range P.P.S.: I know my code will not win any beauty contest.

You are actually looking at the HSV color space. What you can do is:

1 Map your [-148,10] to the [0,360] degree in H

2 Fix the S And V value. (I guess S=1 and V=1 in your case)

3 Get the HSV color from the previous computed H, S, and V

4 Convert HSV color to RGB color and use.

Need Your Help

Pushing the result of a join into a new table?

sql sql-server-2008

New to SQL, been messing around with it a bit. I'm using Microsoft SQL Management Studio 2008. I was wondering if there was a way to push the result of a SQL query into a new table? Anyway, thanks ...

Printing the hex representation of an array of values

c arrays hex type-conversion printf

I was reading a program in C (an implementation of a server/client communication) and I saw this:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.