Ruby, Generate a random hex color (only light colors)

前端 未结 6 2048
甜味超标
甜味超标 2021-01-07 01:49

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 lig

相关标签:
6条回答
  • 2021-01-07 02:19

    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.

    0 讨论(0)
  • 2021-01-07 02:20

    A really nice solution is provided by the color-generator gem, where you can call:

    ColorGenerator.new(saturation: 0.75, lightness: 0.5).create_hex
    
    0 讨论(0)
  • 2021-01-07 02:23

    -- 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))
    
    0 讨论(0)
  • 2021-01-07 02:24

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

    color = (0..2).map{"%0x" % (rand * 0x80 + 0x80)}.join
    
    0 讨论(0)
  • 2021-01-07 02:28

    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".

    0 讨论(0)
  • 2021-01-07 02:28

    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.

    0 讨论(0)
提交回复
热议问题