10

I generate a random color this way:

 var random = new Random();
 var color = String.Format("#{0:X6}", random.Next(0x1000000)); 

How can I exclude colors brighter than a certain value?

Jordan Parmer
  • 36,042
  • 30
  • 97
  • 119
gormit
  • 807
  • 3
  • 9
  • 29
  • I know it's old question. In case someone needs, check this answer. https://stackoverflow.com/a/56848413/2417445 – Krish Jul 02 '19 at 08:36

3 Answers3

12

An quite simple way to get rid of the "upper half" of brightes colors is to mask the result via

random.Next(0x1000000) & 0x7F7F7F
Howard
  • 38,639
  • 9
  • 64
  • 83
7

One way to do this is to generate colours in the HSV/HSL colour-space, and then convert to RGB (the Wikipedia article tells you how to do that).

The advantage of HSV is that one of the components (V) corresponds to "brightness". So if you generate H, S and V independently and randomly, but restrict V to low values, then you will get dark colours.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • here is a [link](http://www.splinter.com.au/converting-hsv-to-rgb-colour-using-c/) on how to do the conversion in c# – Heribert Jun 19 '15 at 07:33
0

You can install ColorHelper library via NuGet and use next code:

using ColorHelper;
RGB rgb = ColorGenerator.GetDarkRandomColor<RGB>();

Instead of RGB class you can use another. E.g.: HEX, CMYK or another.

progm
  • 2,782
  • 3
  • 14
  • 32