Search code examples
c#treeviewrgb

How to blend two RGB colours?


I have a C# application where I have a number of locations and each location has a number of nodes. I ping each location and if it responds it's GREEN, the shade of GREEN depends on the response time; the shorter the response the greener the colour.

If no response to the ping is received then the colour will be RED.

Based on a number of nodes for each location and different possible colours for each node, I want to come up with a colour for the location which is derived from all the child node colours, a blend of its child node colours.

How could I do this?

The control is a TreeView.


Solution

  • Seeing you don't really have an answer here, here’s how I do it in JavaScript.

    I hope it’s not too hard for you to convert to C#.

    // Accepts two hex colors and returns a blended RGB color.
    
    function BlendColors(C1,C2){
    
    var R1=parseInt(C1.substring(1,3),16), G1=parseInt(C1.substring(3,5),16), B1=parseInt(C1.substring(5,7),16);
    
    var R2=parseInt(C2.substring(1,3),16), G2=parseInt(C2.substring(3,5),16), B2=parseInt(C2.substring(5,7),16);
    
    return 'rgb('+Math.round((R1+R2)/2)+','+Math.round((G1+G2)/2)+','+Math.round((B1+B2)/2)+')';}
    

    NB: Alpha channels not taken into consideration.

    In theory, all you gotta do is average the three individual components R/G/B.

    Update:

    Well what do you know... a nice website does language conversions!

    using System;
    
    public static string BlendColors(string C1, string C2)
    {
        int R1 = Convert.ToInt32(C1.Substring(1, 2), 16);
        int G1 = Convert.ToInt32(C1.Substring(3, 2), 16);
        int B1 = Convert.ToInt32(C1.Substring(5, 2), 16);
    
        int R2 = Convert.ToInt32(C2.Substring(1, 2), 16);
        int G2 = Convert.ToInt32(C2.Substring(3, 2), 16);
        int B2 = Convert.ToInt32(C2.Substring(5, 2), 16);
    
        return $"rgb({Math.Round((R1 + R2) / 2.0)},{Math.Round((G1 + G2) / 2.0)},{Math.Round((B1 + B2) / 2.0)})";
    }