Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Random RGB Color

I wrote this C# code snippet here. The idea is to generate a random .NET Color in RGB, while keeping alpha at 255 (i.e. full)

My question is does this function have the potential to hit every colour in RGB space? I thought I was but now I'm second guessing myself. Alternatively is there a better way to do this?

Thanks.

const int COLORSPACE = 0xFF * 0xFF * 0xFF;
const int ALPHA = 0xFF << 24;    

Random _rand = new Random();

Color RandomColor
{
    get
    {
        return Color.FromArgb(_rand.Next(COLORSPACE) + ALPHA);
    }
}
like image 289
Superbeard Avatar asked Oct 23 '12 15:10

Superbeard


People also ask

How do you randomly color in C#?

Random r = new Random(); BackColor = Color. FromArgb(0, 0, r. Next(0, 256));

How do I randomly change color in Java?

Random rand = new Random(); As colours are separated into red green and blue, you can create a new random colour by creating random primary colours: // Java 'Color' class takes 3 floats, from 0 to 1. float r = rand.


1 Answers

Maths contains many of the error. Please put OR into shift hexes NOT MULTIPLE!

Colour use is of much fun and ease in the C# :)

Constant is not needful. ALPHA 255 is of the implicit - simple:

private static readonly Random rand = new Random();

private Color GetRandomColour()
{
    return Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256));
}
like image 110
PRASHANT P Avatar answered Oct 20 '22 10:10

PRASHANT P