Generate Color Gradient in C#
You will have to extract the R, G, B components and perform the same linear interpolation on each of them individually, then recombine.
int rMax = Color.Chocolate.R;
int rMin = Color.Blue.R;
// ... and for B, G
var colorList = new List<Color>();
for(int i=0; i<size; i++)
{
var rAverage = rMin + (int)((rMax - rMin) * i / size);
var gAverage = gMin + (int)((gMax - gMin) * i / size);
var bAverage = bMin + (int)((bMax - bMin) * i / size);
colorList.Add(Color.FromArgb(rAverage, gAverage, bAverage));
}
Oliver's answer was very close... but in my case some of my stepper numbers needed to be negative. When converting the stepper values into a Color
struct my values were going from negative to the higher values e.g. -1 becomes something like 254. I setup my step values individually to fix this.
public static IEnumerable<Color> GetGradients(Color start, Color end, int steps)
{
int stepA = ((end.A - start.A) / (steps - 1));
int stepR = ((end.R - start.R) / (steps - 1));
int stepG = ((end.G - start.G) / (steps - 1));
int stepB = ((end.B - start.B) / (steps - 1));
for (int i = 0; i < steps; i++)
{
yield return Color.FromArgb(start.A + (stepA * i),
start.R + (stepR * i),
start.G + (stepG * i),
start.B + (stepB * i));
}
}
Maybe this function can help:
public IEnumerable<Color> GetGradients(Color start, Color end, int steps)
{
Color stepper = Color.FromArgb((byte)((end.A - start.A) / (steps - 1)),
(byte)((end.R - start.R) / (steps - 1)),
(byte)((end.G - start.G) / (steps - 1)),
(byte)((end.B - start.B) / (steps - 1)));
for (int i = 0; i < steps; i++)
{
yield return Color.FromArgb(start.A + (stepper.A * i),
start.R + (stepper.R * i),
start.G + (stepper.G * i),
start.B + (stepper.B * i));
}
}