CaptTaifun
CaptTaifun

Reputation: 331

Get a color value within a gradient based on a value

Suppose I have the following gradient:

Is there now a calculation or an existing function to read a color value from this gradient based on a value that changes every second?

As a thought of mine: One could, e.g. in Photoshop, create an image, say 100px wide and 1px high. Now I lay a color gradient with the values and points mentioned above over the complete surface. The value, over which I want to get the color, is also only between the int values 0 and 100. So I could load this image into a variable or so (without displaying it in the UI) and get the color based on my value with a "GetPixel" function, so if e.g. the value is 50, I would get orange, because the 50th pixel in the image corresponds to orange. This would be a possibility that is plausible and (theoretically) easy to program.

But now the value changes every second. And I think I read somewhere that the GetPixel function is relatively slow. Of course I could just program it out now (which I'll probably do afterwards for testing purposes), but it seems to me to be very resource intensive. Is there a better alternative?

Upvotes: 1

Views: 2486

Answers (1)

NetMage
NetMage

Reputation: 26917

Here is a simple linear interpolation between the colors in the RGB space using System.Drawing.Color to hold the colors:

public int LinearInterp(int start, int end, double percentage) => start + (int)Math.Round(percentage * (end - start));
public Color ColorInterp(Color start, Color end, double percentage) =>
    Color.FromArgb(LinearInterp(start.A, end.A, percentage),
                   LinearInterp(start.R, end.R, percentage),
                   LinearInterp(start.G, end.G, percentage),
                   LinearInterp(start.B, end.B, percentage));
public Color GradientPick(double percentage, Color Start, Color Center, Color End) {
    if (percentage < 0.5)
        return ColorInterp(Start, Center, percentage / 0.5);
    else if (percentage == 0.5)
        return Center;
    else
        return ColorInterp(Center, End, (percentage - 0.5)/0.5);
}

And you would use it like this:

var Start = Color.FromArgb(255, 0, 255, 0);
var Center = Color.FromArgb(255, 255, 165, 0);
var End = Color.FromArgb(255, 255, 0, 0);

var Pick = GradientPick(0.75, Start, Center, End);

Upvotes: 4

Related Questions