Ruby, Generate a random hex color (only light colo

2020-03-06 19:41发布

I know this is possible duplicated question. Ruby, Generate a random hex color

My question is slightly different. I need to know, how to generate the random hex light colors only, not the dark.

5条回答
Lonely孤独者°
2楼-- · 2020-03-06 19:50

Just some pointers:

Use HSL and generate the individual values randomly, but keeping L in the interval of your choosing. Then convert to RGB, if needed.

It's a bit harder than generating RGB with all components over a certain value (say 0x7f), but this is the way to go if you want the colors distributed evenly.

查看更多
Animai°情兽
3楼-- · 2020-03-06 19:50

I modified one of the answers from the linked question (Daniel Spiewak's answer) to come up with something that is pretty flexible in terms of excluding darker colors:

floor = 22 # meaning darkest possible color is #222222
r = (rand(256-floor) + floor).to_s 16
g = (rand(256-floor) + floor).to_s 16
b = (rand(256-floor) + floor).to_s 16

[r,g,b].map {|h| h.rjust 2, '0'}.join

You can change the floor value to suit your needs. A higher value will limit the output to lighter colors, and a lower value will allow darker colors.

查看更多
狗以群分
4楼-- · 2020-03-06 20:04

In this thread colour lumincance is described with a formula of

(0.2126*r) + (0.7152*g) + (0.0722*b)

The same formula for luminance is given in wikipedia (and it is taken from this publication). It reflects the human perception, with green being the most "intensive" and blue the least.

Therefore, you can select r, g, b until the luminance value goes above the division between light and dark (255 to 0). For example:

lum, ary = 0, []
while lum < 128
 ary = (1..3).collect {rand(256)}
 lum = ary[0]*0.2126 + ary[1]*0.7152 + ary[2]*0.0722
end

Another article refers to brightness, being the arithmetic mean of r, g and b. Note that brightness is even more subjective, as a given target luminance can elicit different perceptions of brightness in different contexts (in particular, the surrounding colours can affect your perception).

All in all, it depends on which colours you consider "light".

查看更多
叛逆
5楼-- · 2020-03-06 20:05

All colors where each of r, g ,b is greater than 0x7f

color = (0..2).map{"%0x" % (rand * 0x80 + 0x80)}.join
查看更多
老娘就宠你
6楼-- · 2020-03-06 20:12

-- I found that 128 to 256 gives the lighter colors

    Dim rand As New Random
    Dim col As Color
    col = Color.FromArgb(rand.Next(128, 256), rand.Next(128, 256), rand.Next(128, 256))
查看更多
登录 后发表回答