Alex Rivera | Logout

Generate color gradient in C#

Asked 2010-01-06T09:02:29.963
30

My question here is similar to the question here, except that I am working with C#.

I have two colors, and I have a predefine steps. How to retrieve a list of Colors that are the gradients between the two?

This is an approach that I tried, which didn't work:

int argbMax = Color.Chocolate.ToArgb();
int argbMin = Color.Blue.ToArgb();
var colorList = new List<Color>();

for(int i=0; i<size; i++)
{
    var colorAverage= argbMin + (int)((argbMax - argbMin) *i/size);
    colorList.Add(Color.FromArgb(colorAverage));
}

If you try the above code, you will find that a gradual increase in argb doesn't correspond to a visual gradual increase in the color.

Any idea on this?

Edit
Report

1 Answer

8
    public static List<Color> GetGradientColors(Color start, Color end, int steps)
    {
        return GetGradientColors(start, end, steps, 0, steps - 1);
    }

    public static List<Color> GetGradientColors(Color start, Color end, int steps, int firstStep, int lastStep)
    {
        var colorList = new List<Color>();
        if (steps <= 0 || firstStep < 0 || lastStep > steps - 1)
            return colorList;

        double aStep = (end.A - start.A) / steps;
        double rStep = (end.R - start.R) / steps;
        double gStep = (end.G - start.G) / steps;
        double bStep = (end.B - start.B) / steps;

        for (int i = firstStep; i < lastStep; i++)
        {
            var a = start.A + (int)(aStep * i);
            var r = start.R + (int)(rStep * i);
            var g = start.G + (int)(gStep * i);
            var b = start.B + (int)(bStep * i);
            colorList.Add(Color.FromArgb(a, r, g, b));
        }

        return colorList;
    }
answered 2012-10-11T16:16:13.013

Your Answer