wpfcode-behindbrush

How to generate 12 different Brush Colors at run time (12 is a number that may vary)


I want to generate 12 different visible Brush Colors in WPF in my code behind and the number of colors which is initially 12 may vary as the application evolves i.e. I want to generate as many different visible Brush Colors depending on a given count?

I would explain it a little more:

I am creating Rectangles in a for loop and for each rectangle created at run time I have to assign a Fill Color e.g.

    for (i=0; i<12; i++)
    {
        Rectangle rect = new Rectangle();
        rect.Fill = <I want to assign a unique visible color>;
        rect.Stroke = Brushes.Black;
        rect.StrokeThickness = 1;
    }

Solution

  • What you probably need is an RGB to HSL, and HSL to RGB converter. You can then divide the total hue (usually represented as degrees in a circle, but sometimes a percent value) by the number of colors required. Incrementing the hue value by the segment amount should produce the most differentiated colors possible.

    Most examples use the WinForms Color object since it was able to provide H S and L values. There are lots of online examples:

    https://web.archive.org/web/20141023005253/http://bobpowell.net/RGBHSB.aspx

    how to use HSL in Asp.net