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?
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.
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.
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.