.NET Random RGB Color

14,084

Solution 1

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.

Solution 2

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));
}
Share:
14,084
Superbeard
Author by

Superbeard

I work with real-time database systems at a private not-for-profit company.

Updated on June 07, 2022

Comments

  • Superbeard
    Superbeard almost 2 years

    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);
        }
    }
    
  • Tejs
    Tejs over 11 years
    Plus, unless there is a performance reason, I would figure Color.FromArgb(_rand.Next(256), _rand.Next(256), _rand.Next(256), ALPHA) would randomly get you a RGB value, plus the alpha without potentially funky math.
  • harold
    harold over 11 years
    @Tejs adding the alpha like that is fine, really. But perhaps not as clear as it could be.
  • and_the_rand
    and_the_rand over 11 years
    @Tejs: In that FromArgb call, alpha is the first argument.
  • Superbeard
    Superbeard over 11 years
    Oh in know that Color.FromArgb(red,green,blue) would get me what I want. It's part performance, part because I simply think three calls to _rand.Next() looks ugly. Also thank you for the answer @harold, next time I'll have to remember to check on my calculator.
  • harold
    harold over 11 years
    @Superbeard you're welcome. A calculator isn't necessary perhaps. The idea to multiply the number of values each part could have would be correct, only a byte can have 0x100 different values (which includes zero). So on intuition alone, it shouldn't be 0xFF * 0xFF * 0xFF.
  • japreiss
    japreiss over 11 years
    I would replace the addition with a bitwise OR. Both will have the same effect, but most programmers would use a bitwise OR. Your code will be easier to understand.