Evaluate whether a HEX value is dark or light

前端 未结 4 859
难免孤独
难免孤独 2020-12-28 20:03

The user of the ASP.NET web app I\'m building can select colors for use on some of the elements (e.g. buttons/titles) to facilitate some degree of personalisation.

4条回答
  •  半阙折子戏
    2020-12-28 20:58

    Instead of adding the RGB components together like the other answerer (ricknz) said, you should actually take the average of them.

    Also, since green is more visible to the human eye than blue, you should also add a weight.

    So you have to multiply the Red component first times 0.299, the Green times 0.587 and the Blue times 0.114

    so the luminance is given by: Luminance = (r*0.299 + g*0.587 + b*0.114)/3

    edit: here is a snippet which calculates it:

     float calcLuminance(int rgb)
     {
          int r = (rgb & 0xff0000) >> 16;
          int g = (rgb & 0xff00) >> 8;
          int b = (rgb & 0xff);
    
          return (r*0.299f + g*0.587f + b*0.114f) / 256;
     }
    

    p.s. the division by 256 since we the RGB ran from 0-256 (instead of 0-1)

    edit: changed the calculcation as to divide by 256 and not 768 as cleverly commented

提交回复
热议问题