简体   繁体   中英

Get a color value within a gradient based on a value

Suppose I have the following gradient:

  • Start (0): Green (0, 255, 0)
  • Center (0.5): Orange (255, 165, 0)
  • End (1): Red (255, 0, 0)

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, eg 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 eg 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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM