Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a random hex string that represents a color?

I'm generating some charts that need a hex string for the colors.

Example:

<dataseries name="ford" color="FF00FF" /> 

I'm creating these dynamically, so I would like to generate the hex code for each dataseries randomly.

What is the best way to do this?

like image 670
rahkim Avatar asked Apr 08 '09 15:04

rahkim


People also ask

How do you generate a random hex code?

In this version of the function we use Math. round() and Math. random() * 15 to generate a random number between 0 and 15, and then convert that number to its hexadecimal equivalent using . toString(16) , and append that newly generated digit to the hexCode base until we have 6 digits.

How do you represent colors in hexadecimal?

Hex color codes start with a pound sign or hashtag (#) and are followed by six letters and/or numbers. The first two letters/numbers refer to red, the next two refer to green, and the last two refer to blue. The color values are defined in values between 00 and FF (instead of from 0 to 255 in RGB).

How is the hex value of color represented in HTML?

A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB (blue) hexadecimal integers specify the components of the color.


2 Answers

Easiest way is to use String.Format and use the hexadecimal format for the argument.

var random = new Random(); var color = String.Format("#{0:X6}", random.Next(0x1000000)); // = "#A197B9" 
like image 137
Samuel Avatar answered Sep 19 '22 18:09

Samuel


Samuel's answer is the best way to do this, just make sure that if you're generating the colors inside a loop that you don't instantiate a new Random object each time because new Random() seeds the generator using the system clock. Your loop is going to run faster than the clock can tick, so you'll end up generating several of the same colors over and over because random is being seeded with the same value.

It should look something like this:

int numColors = 10; var colors = new List<string>(); var random = new Random(); // Make sure this is out of the loop! for (int i = 0; i < numColors; i++)  {     colors.Add(String.Format("#{0:X6}", random.Next(0x1000000))); } 

instead of:

int numColors = 10; var colors = new List<string>(); for (int i = 0; i < numColors; i++)  {     var random = new Random(); // Don't put this here!     colors.Add(String.Format("#{0:X6}", random.Next(0x1000000))); } 
like image 35
John Rasch Avatar answered Sep 21 '22 18:09

John Rasch