How to remove white related colors in KnowColor C#

283 Views Asked by At

Currently im using this method for generating randomized KnownColor used for DataGriView cell background-color.

    public static Color GetRandomizedKnownColor()
    {
        Random randomGen = new Random();
        KnownColor[] names = (KnownColor[])Enum.GetValues(typeof(KnownColor));
        KnownColor randomColorName = names[randomGen.Next(names.Length)];
        Color randomColor = Color.FromKnownColor(randomColorName);
        return randomColor;
    }

Now i want to remove all white related KnowColors so that all possible generated color is not in contrast with the white DataGriView cell background-color in my application.

1

There are 1 best solutions below

4
On BEST ANSWER

This is how I would do it:

static private Random randomGen = new Random();
public static Color GetRandomizedKnownColor()
{
    int number;
    do
    {
        number = randomGen.Next(28, 168);
    } while (number == (int)KnownColor.White);

    return Color.FromKnownColor((KnownColor)number);
}

Note that your Random object will always return the same value in your code.

KnownColor elements from 28 to 167 are actual colors while the rest refer to control colors (like ActiveCaptionText, InactiveBorder, etc). If you actually want all KnownColors and skip all white colors (there are other [255,255,255] besides "White"), you should use this code instead:

Color randomColor;
do
{
    randomColor = Color.FromKnownColor((KnownColor)randomGen.Next(1, 175));
} while (randomColor.R + randomColor.G + randomColor.B == 255 * 3);
return randomColor;

If you want to skip also very light colors, you can use a condition like this, for example:

} while (randomColor.R + randomColor.G + randomColor.B >= 250 * 3);