JavaScript:
function color2rgb(color) {
var r = parseInt(color.substr(1, 2), 16);
var g = parseInt(color.substr(3, 2), 16);
var b = parseInt(color.substr(5, 2), 16);
return new Array(r, g, b);
}
function rgb2color(rgb) {
var s = "#";
for (var i = 0; i < 3; i++) {
var c = Math.round(rgb[i]).toString(16);
if (c.length == 1)
c = '0' + c;
s += c;
}
return s.toUpperCase();
}
var ColorA = color2rgb("#69bf7b");
var ColorB = color2rgb("#f8696b");
function gradient(num) {
if (num > 40) {
return "#e33e24";
}
var Gradient = new Array();
for (var i = 0; i < 3; i++) {
Gradient[i] = ColorA[i] + (ColorB[i] - ColorA[i]) / 40 * num;
}
return rgb2color(Gradient);
}
c#:
public class GradientColor
{
private double MaxLevel = 100;
private string ColorFrom = null;
private string ColorTo = null;
private int[] ColorA = null;
private int[] ColorB = null;
/// <summary>
/// Color Helper
/// </summary>
/// <param name="colorFrom">#000000 format</param>
/// <param name="colorTo">#000000 format</param>
/// <param name="maxLevel"></param>
public GradientColor(string colorFrom, string colorTo, double maxLevel)
{
if (string.IsNullOrEmpty(colorFrom)
|| string.IsNullOrEmpty(colorTo)
|| colorFrom.Length != 7
|| colorTo.Length != 7
|| maxLevel <= 0)
{
throw new Exception("Invalid parameter.");
}
this.MaxLevel = maxLevel;
this.ColorFrom = colorFrom;
this.ColorTo = colorTo;
ColorA = Color2rgb(colorFrom);
ColorB = Color2rgb(colorTo);
}
private int[] Color2rgb(string color)
{
var r = Convert.ToInt32(color.Substring(1, 2), 16);
var g = Convert.ToInt32(color.Substring(3, 2), 16);
var b = Convert.ToInt32(color.Substring(5, 2), 16);
return new int[] { r, g, b };
}
private string Rgb2color(double[] rgb)
{
var s = "";
for (int i = 0; i < rgb.Length; i++)
{
var c = Convert.ToString((int)Math.Round(rgb[i]), 16);
if (c.Length == 1)
{
c = '0' + c;
}
s += c;
}
return s.ToUpper();
}
public string Gradient(double level)
{
if (level > MaxLevel)
{
return ColorTo;
}
var gradient = new double[3];
for (var i = 0; i < 3; i++)
{
gradient[i] = ColorA[i] + (ColorB[i] - ColorA[i]) / MaxLevel * level;
}
return Rgb2color(gradient);
}
}