How to generate random color names in C#
Use Enum.GetValue
to retrieve the values of the KnownColor
enumeration and get a random value:
Random randomGen = new Random();
KnownColor[] names = (KnownColor[]) Enum.GetValues(typeof(KnownColor));
KnownColor randomColorName = names[randomGen.Next(names.Length)];
Color randomColor = Color.FromKnownColor(randomColorName);
Get Random Color
Here's the answer I started posting before you deleted and then un-deleted your question:
public partial class Form1 : Form
{
private Random rnd = new Random();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Color randomColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
BackColor = randomColor;
}
}
Generate random color
You could try this one:
Random rnd = new Random();
Byte[] b = new Byte[3];
rnd.NextBytes(b);
Color color = Color.FromRgb(b[0],b[1],b[2]);
For more information about the NextBytes
method please have a look here.
Random color in C#
Just tried this in LinqPad and it seemed to do the trick:
var random = new Random();
System.Drawing.Color c;
unchecked
{
var n = (int)0xFF000000 + (random.Next(0xFFFFFF) & 0x7F7F7F);
Console.WriteLine($"ARGB: {n}");
c = System.Drawing.Color.FromArgb(n);
}
Console.WriteLine($"A: {c.A}");
Console.WriteLine($"R: {c.R}");
Console.WriteLine($"G: {c.G}");
Console.WriteLine($"B: {c.B}");
More concisely, it would be:
var random = new Random();
Color c;
unchecked
{
c = Color.FromArgb((int)0xFF000000 + (random.Next(0xFFFFFF) & 0x7F7F7F));
}
Or if you want to get really funky with bit manipulation (this is not more efficient, just saves you typing some 0s):
c = Color.FromArgb((int)(0xFF << 24 ^ (random.Next(0xFFFFFF) & 0x7F7F7F)));
Original poster pointed out that an extra pair of brackets eliminates the need for unchecked:
c = Color.FromArgb((int)(0xFF000000 + (random.Next(0xFFFFFF) & 0x7F7F7F)));
Bit of an explanation. ARGB is using a signed 32 bit int to represent four bytes, A, R, G, and B. We want the colour to be solid, so A needs to be 255 hence:
0xFF000000
Then random.Next(0xFFFFFF) generates a pseudo-random 24 bit number taking care of the R, G and B bytes. As the question only wanted dark colours we mask off the most significant bit of each byte. For a simple example, say the RNG spat out the max value (equivalent to white):
0xFFFFFF = 111111111111111111111111
We then do a bitwise AND to chop off the most significant bits:
0x7F7F7F = 011111110111111101111111
111111111111111111111111 & 011111110111111101111111 = 011111110111111101111111
Select a Random Color from a List
Try this simple example:
static Color[] colors = { Color.Red, Color.Green... };
static Color GetRandomColor()
{
var random = new Random();
return colors[random.Next(colors.Length)];
}
And don't forget using System.Drawing
.
How to generate random color?
If you want to use the standard console colors, you could mix the ConsoleColor Enumeration and Enum.GetNames() to get a random color. You'd then use Console.ForegroundColor and/or Console.BackgroundColor to change the color of the console.
// Store these as static variables; they will never be changing
String[] colorNames = ConsoleColor.GetNames(typeof(ConsoleColor));
int numColors = colorNames.Length;
// ...
Random rand = new Random(); // No need to create a new one for each iteration.
string[] x = new string[] { "", "", "" };
while(true) // This should probably be based on some condition, rather than 'true'
{
// Get random ConsoleColor string
string colorName = colorNames[rand.Next(numColors)];
// Get ConsoleColor from string name
ConsoleColor color = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), colorName);
// Assuming you want to set the Foreground here, not the Background
Console.ForegroundColor = color;
Console.WriteLine((x[rand.Next(x.Length)]));
Thread.Sleep(100);
}
Best way to generate random Color and exclude old one
I would take a different approach:
- Generate a random integer in [0; 2] representing red, green, blue
- Add 0.5 to the color just determined in the first step but subtract -1 if greater than 1
- Generate 2 independent random float numbers in the range [0; 1] that are taken for the remaining two color components
Example: Assume we have C1 = (R1; G1; B1) = (0.71; 0.22; 0.83)
- Assume step 1 produces index 0 i.e. red
- So we take R1 + 0.5 = 0.71 + 0.5f = 0.21f
- We create G2 and B2 as new green and blue components and get (0.21f; G2; B2)
Even if G2 and B2 are identical to their predecessors the new color will be clearly distinct as R2 is shifted
Update code
public static class RandomColorGenerator
{
public static Color GetNextPseudoRandomColor(Color current)
{
int keep = new System.Random().Next(0, 2);
float red = UnityEngine.Random.Range(0f, 1f);
float green = UnityEngine.Random.Range(0f, 1f);
float blue = UnityEngine.Random.Range(0f, 1f);
Color c = new Color(red, green, blue);
float fixedComp = c[keep] + 0.5f;
c[keep] = fixedComp - Mathf.Floor(fixedComp);
return c;
}
}
Test:
public class RandomColorTest
{
[Test]
public void TestColorGeneration()
{
Color c = Color.magenta;
for (int i = 0; i < 100; i++)
{
Vector3 pos = new Vector3(i / 20f, 0f, 0f);
c = RandomColorGenerator.GetNextPseudoRandomColor(c);
Debug.Log(i + " = " + c);
Debug.DrawRay(pos, Vector3.up, c);
}
}
}
Result in scene view around (0; 0; 0) after running editor test
Related Topics
Dynamically Updating Tabcontrol Content at Runtime
Xml File Creation Using Xdocument in C#
External Handler for Msiexec Msisetexternalui
Convert Data Type from Inherited Classes in C#
Windows 7 Progress Bar in Taskbar in C#
How to Compile and Run C# Program Without Using Visual Studio
How to Force Bundlecollection to Flush Cached Script Bundles in MVC4
How to Mock Configurationmanager.Appsettings with Moq
Working with C# Anonymous Types
Ms Chart Rectangular Annotation Width in Percent and Not Pixel
Installing Windows Service Programmatically
How to Open a Web Page from My Application
Differencebetween Property and Dependency Property