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

前端 未结 6 2082
甜味超标
甜味超标 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: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.

提交回复
热议问题