views:

110

answers:

3

I have two colors in my .NET application that are user defined. I'd like to somehow get the color in between those two colors. It's the color in the middle of the gradient. Is there any way to accomplish this?

+6  A: 

By color do you mean an instance of Color struct?

If so, just take every of the R, G and B components in turn, and compute average for each. Combine the result to get your blended color.

Pavel Minaev
+13  A: 

Well, the simplest way is to take the average of each of the red, green, blue and alpha values:

Color c1 = ...;
Color c2 = ...;
Color midpoint = Color.FromArgb((c1.A + c2.A) / 2,
                                (c1.R + c2.R) / 2,
                                (c1.G + c2.G) / 2,
                                (c1.B + c2.B) / 2);

Even though the A, R, G and B properties are bytes, they'll be promoted to ints before addition, so there won't be an overflow problem. The result of the division will still be in the range [0, 255] and FromArgb takes Int32 values but discards everything other than the lowest 8 bits - just what we want.

An alternative would be to use a different colour model (e.g. HSV) but that would be somewhat more complicated. For gradients, this should do fine.

Jon Skeet
That worked great. I also had to round to the nearest whole number or it would crash in some cases. Here is the VB code I ended up using:MyColor = Color.FromArgb( _Decimal.Round(((CInt(Color1.A) + CInt(Color2.A)) / 2)), _Decimal.Round(((CInt(Color1.R) + CInt(Color2.R)) / 2)), _Decimal.Round(((CInt(Color1.G) + CInt(Color2.G)) / 2)), _Decimal.Round(((CInt(Color1.B) + CInt(Color2.B)) / 2)) _)
Jeff Stock
You don't need to do all the decimal stuff - just use \ instead of / to make it use integer division. Do you have Option Strict turned Off? I wouldn't expect it to compile otherwise.
Jon Skeet
+7  A: 

Averaging is the best answer, but a word of caution:

An issue of color averages is that unless they're within the same thematic family, (high R, low G, low B) you'll end up trending towards grey.

Note that the more you use the averaging function, the more grey the result will become.