简体   繁体   中英

.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 (ie 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);
    }
}

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));
}

No. The (exclusive!) upper bound should be 0x1000000, not 0xFF * 0xFF * 0xFF.

0xFF * 0xFF * 0xFF is only 0xFD02FF, so you're missing that colour and all higher colours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM