Monday, December 15, 2008

How to: Blend colors with GDI+

Once I needed to build a heat map chart usign different colors spread on a given numeric interval. Here is the GDI+ code I used to create all the intermediate colors between the start color and the end color.

Blend colors with GDI+

In order to blend the two colors using a specified number of stages I decrees the color amount of the start color and increes it for the end color. I do this for each RGB channel.

Here is my GDI+ color blender: Blend colors with GDI+

C# .NET

private Color[] BlendColors(Color start, Color end, int steps)

{

    Color[] colorPalette = new Color[steps];

    double colorFactor = 100 / Convert.ToDouble(steps) / 100;

 

    for (int colorLevel = 0; colorLevel < steps; colorLevel++)

    {

        double endColorQuantity = (colorLevel + 1) * colorFactor;

        double startColorQuantity = 1 - endColorQuantity;

 

        colorPalette[colorLevel] = Color.FromArgb(255,

        Math.Abs(Convert.ToInt32(end.R * endColorQuantity + start.R * startColorQuantity)),

        Math.Abs(Convert.ToInt32(end.G * endColorQuantity + start.G * startColorQuantity)),

        Math.Abs(Convert.ToInt32(end.B * endColorQuantity + start.B * startColorQuantity)));

 

    }

 

    return colorPalette;

}



kick it on DotNetKicks.com

No comments: