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?
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.
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).
A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB (blue) hexadecimal integers specify the components of the color.
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"
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))); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With