Random Color from Known Color List

Some one in an asp.net forum asked how to select a random color from the list of known colors so I wrote a little code to do this. I wrote a GetRandomColor and GetRandomNumber method which uses the RandomNumberGenerator from the System.Security.Cryptography namespace. As far as I know this is the best random number generator built into the .Net Framework.

using System.Drawing;
using System.Security.Cryptography;

...
public static Color GetRandomColor() {   KnownColor[] colors = (KnownColor[])Enum.GetValues(typeof(KnownColor));      return Color.FromKnownColor(colors[GetRandomNumber(colors.Length)]);   }
public static int GetRandomNumber(int maxValue) {   RandomNumberGenerator rng = RNGCryptoServiceProvider.Create();
  byte[] bytes = new byte[4];
  rng.GetBytes(bytes);
  int ranNum = BitConverter.ToInt32(bytes, 0);
  return Math.Abs(ranNum % maxValue); }
Published Monday, May 26, 2003 10:47 PM by puzzlehacker

Comments

# re: Random Color from Known Color List

I can't say I have used the CryptoServices as a RNG before so I gave it a shot. I came up with the following -
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(bytes);

I am not too sure about the 'ranNum' and its use with the 'mod' function. Would you get the same random distribution if you took the absolute value of 'ranNum' first and then do the 'mod' with maxValue?

Monday, May 26, 2003 9:25 PM by SBC

# re: Random Color from Known Color List

Oh, this is wonderfull!!

I wish all my programmers would use things like this :-)

Thursday, August 02, 2007 5:04 AM by Gerald

# re: Random Color from Known Color List

Thanks...

Thats helpful

Friday, June 20, 2008 3:00 AM by Sam

# re: Random Color from Known Color List

its great...

but how to avoid dark color???

Tuesday, July 08, 2008 5:13 AM by lim

# re: Random Color from Known Color List

Thanks, its very helpful.

Thanks again.

Wednesday, July 09, 2008 1:24 AM by Buddika

# re: Random Color from Known Color List

great !!

how to avoid light colors !!

Friday, October 10, 2008 1:54 AM by Manoj

# re: Random Color from Known Color List

Thanx!

But how to know whether the color is already choosen once by any user.

Monday, December 08, 2008 9:41 AM by Adya

# re: Random Color from Known Color List

Gud one!!

Is there any way to avoid dark colors which when set in the <td> background color would not hide the text in the <td>??

Friday, September 25, 2009 7:29 AM by Saurabh

Leave a Comment

(required) 
(required) 
(optional)
(required)