Code:
using Zaczero;
(..)
var gradient = new Gradient();
gradient.Add(new GradientColor(0.0, "#ED4264"));
gradient.Add(new GradientColor(0.4, "#4286fF"));
gradient.Add(new GradientColor(1.0, "#FFEDBC"));
var coolColor = gradient.Calculate(0.65);
Code:
using System;
using System.Collections.Generic;
using System.Globalization;
namespace Zaczero
{
public struct GradientColor : IComparable<GradientColor>
{
public double Offset;
public double R;
public double G;
public double B;
public double A;
public GradientColor(double offset, double r, double g, double b, double a)
{
Offset = offset;
R = r;
G = g;
B = b;
A = a;
}
public GradientColor(double offset, double r, double g, double b)
{
Offset = offset;
R = r;
G = g;
B = b;
A = 1d;
}
public GradientColor(double offset, string code)
{
const string invalidColorCode = "Invalid color code";
Offset = offset;
code = code.TrimStart('#');
foreach (var c in code)
{
if (!char.IsLetterOrDigit(c))
{
throw new ArgumentException(invalidColorCode);
}
}
if (code.Length == 6)
{
code += "FF";
}
if (code.Length == 8)
{
var r = code.Substring(0, 2);
var g = code.Substring(2, 2);
var b = code.Substring(4, 2);
var a = code.Substring(6, 2);
R = byte.Parse(r, NumberStyles.HexNumber) / 255d;
G = byte.Parse(g, NumberStyles.HexNumber) / 255d;
B = byte.Parse(b, NumberStyles.HexNumber) / 255d;
A = byte.Parse(a, NumberStyles.HexNumber) / 255d;
}
else
{
throw new ArgumentException(invalidColorCode);
}
}
public int CompareTo(GradientColor other)
{
return Offse*****mpareTo(other.Offset);
}
}
public class Gradient
{
private readonly List<GradientColor> _colors;
public Gradient()
{
_colors = new List<GradientColor>();
}
public void Add(GradientColor color)
{
_colors.Add(color);
_colors.Sort();
}
public GradientColor Calculate(double offset)
{
var colorStart = default(GradientColor);
var colorEnd = default(GradientColor);
for (var i = 1; i < _colors.Count; i++)
{
if (_colors[i].Offset > offset)
{
colorStart = _colors[i - 1];
colorEnd = _colors[i];
break;
}
}
var offsetRange = colorEnd.Offset - colorStart.Offset;
var offsetPercentage = (offset - colorStart.Offset) / offsetRange;
var offsetPercentageInv = 1 - offsetPercentage;
return new GradientColor(offset,
colorStart.R * offsetPercentageInv + colorEnd.R * offsetPercentage,
colorStart.G * offsetPercentageInv + colorEnd.G * offsetPercentage,
colorStart.B * offsetPercentageInv + colorEnd.B * offsetPercentage,
colorStart.A * offsetPercentageInv + colorEnd.A * offsetPercentage);
}
}
}