Choose a random color other than certain colors.
I am currently using this code:
Random randomColor = new Random();
KnownColor[] names = (KnownColor[])Enum.GetValues(typeof(KnownColor));
KnownColor randomColorName = names[randomColor.Next(names.Length)];
Color RandomColor = Color.FromKnownColor(randomColorName);
this.BackColor = RandomColor;
I use this to create a random color and set it to my background, but I don't want it to go black.
Is there a way to remove black from possible random colors?
+3
source to share
3 answers
Option 1: Just use the list delete method:
List<KnownColor> namesList = new List<KnownColor>((KnownColor[])Enum.GetValues(typeof(KnownColor)));
namesList.Remove(KnownColor.Black);
KnownColor[] names = namesList.ToArray();
Option 2: Use only a list. They have much more control than arrays:
Random randomColor = new Random();
List<KnownColor> names = new List<KnownColor>((KnownColor[])Enum.GetValues(typeof(KnownColor)));
names.Remove(KnownColor.Black);
this.BackColor = Color.FromKnownColor(names[randomColor.Next(names.Count)]);
Addition: You can also remove all colors that are black but not called black (like ActiveCaption):
List<KnownColor> names = new List<KnownColor>((KnownColor[])Enum.GetValues(typeof(KnownColor)));
foreach (KnownColor i in names)
{
if (Color.FromKnownColor(i).ToArgb() == Color.Black.ToArgb()) names.Remove(i);
}
+9
source to share
After that, how do I filter the colors (in this example, I remove the black and white colors from the color list) from the KnownColor and return a random color:
private Color getRandomColor()
{
Random randomGen = new Random();
KnownColor[] names = (KnownColor[])Enum.GetValues(typeof(KnownColor));
KnownColor[] badColors = { KnownColor.Black, KnownColor.White };
IEnumerable<KnownColor> colors = names.Except(badColors);
var okColors = colors.ToArray();
KnownColor randomColorName = okColors[randomGen.Next(names.Length)];
return Color.FromKnownColor(randomColorName);
}
0
source to share