.netvisual-studio

Get blend of two colors in .NET


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?


Solution

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