Search code examples
c#system.drawing

Set color through color code in c#


I am trying to add color in c# code, with the following color code for example.

ListTreeView.Background = new SolidColorBrush(Colors.White);

This is working..but I want to add this color as color code so I am add as

System.Windows.Media

Could someone give me an example with

System.Drawing

So what I can do the following:

ListTreeView.Background = ColorTranslator.FromHtml("#FFE7EFF2");

This gives me error ; Any Ideas?


Solution

  • There isn't an easy way to get the colour with alpha included from a hex string in this way.

    I think your answer depends on where you're getting the colour and alpha values from.

    The RGB colour alone can be parsed from an HTML hex string:

    Color colour = ColorTranslator.FromHtml("#E7EFF2");
    

    If you have a separate alpha value you can then apply this (docs):

    Color colour = ColorTranslator.FromHtml("#E7EFF2");
    Color transparent = Color.FromArgb(128, colour);
    

    Alternatively you may need to parse the string and split it out to convert the hex pairs into integer values.

    PS excuse English spelling, but colour should definitely have a 'u' in it :)