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

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

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

提交回复
热议问题