Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Color Gradient in C#

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?

like image 370
Graviton Avatar asked Jan 06 '10 09:01

Graviton


1 Answers

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)); } 
like image 159
David M Avatar answered Sep 22 '22 08:09

David M