Explanation
First off, my answer is an adapted version of this: Calculate color values from green to red. I decided to create a Java version of that JavaScript solution. Code which you can directly plug-in into your code without transferring everything yourself.
The idea is to use the HSL (hue, saturation, lightness) color space instead of RGB (red, green, blue). There red is represented by the hue value 0°
and green by 120°
with yellow in between at 60°
with smooth transitions in terms of hue:

We will fix a saturation of 100%
and a lightness of 50%
but you can play with these values if you like.
Usage
Here is how you would use it in your code:
// A value between 1.0 (green) to 0.0 (red)
double percentage = ...
// Get the color (120° is green, 0° is red)
Color color = transitionOfHueRange(percentage, 120, 0);
And that would be the resulting range:

Other methods
Here is the transitionOfHueRange
method. It accepts a percentage
value between 0.0
and 1.0
and a hue
range between 0
and 360
:
public static Color transitionOfHueRange(double percentage, int startHue, int endHue) {
// From 'startHue' 'percentage'-many to 'endHue'
// Finally map from [0°, 360°] -> [0, 1.0] by dividing
double hue = ((percentage * (endHue - startHue)) + startHue) / 360;
double saturation = 1.0;
double lightness = 0.5;
// Get the color
return hslColorToRgb(hue, saturation, lightness);
}
Here is the hslColorToRgb
function. It accepts HSL values from 0.0
to 1.0
:
public static Color hslColorToRgb(double hue, double saturation, double lightness) {
if (saturation == 0.0) {
// The color is achromatic (has no color)
// Thus use its lightness for a grey-scale color
int grey = percToColor(lightness);
return new Color(grey, grey, grey);
}
double q;
if (lightness < 0.5) {
q = lightness * (1 + saturation);
} else {
q = lightness + saturation - lightness * saturation;
}
double p = 2 * lightness - q;
double oneThird = 1.0 / 3;
double red = percToColor(hueToRgb(p, q, hue + oneThird));
double green = percToColor(hueToRgb(p, q, hue));
double blue = percToColor(hueToRgb(p, q, hue - oneThird));
return new Color(red, green, blue);
}
The hueToRgb
method:
public static double hueToRgb(double p, double q, double t) {
if (t < 0) {
t += 1;
}
if (t > 1) {
t -= 1;
}
if (t < 1.0 / 6) {
return p + (q - p) * 6 * t;
}
if (t < 1.0 / 2) {
return q;
}
if (t < 2.0 / 3) {
return p + (q - p) * (2.0 / 3 - t) * 6;
}
return p;
}
And finally the small utility method percToColor
:
public static int percToColor(double percentage) {
return Math.round(percentage * 255);
}