评价一个十六进制值是否太暗或太亮 [英] Evaluate whether a HEX value is dark or light

查看:158
本文介绍了评价一个十六进制值是否太暗或太亮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET Web应用程序我建立可以选择一些元素使用的颜色(例如按钮/游戏),以促进某种程度的个性化的用户。

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.

问题是,默认情况下对这些层的文字为黑色......我想要做的就是编程评估黑白文本之间通过选择器由用户选择的HEX值,开关 - 这可以在JavaScript或在code的后面。

The problem is that by default the text on those layers is black...what I'm trying to do is to evaluate the HEX value chosen by the user through a picker, and switch between black and white text programmatically - this can be in JavaScript, or in code behind.

问题的症结是,我只是不知道如何评价HEX做出决定所选择的彩转黑的接近是否过于接近使用黑色文本。

The crux of the problem is that I'm just not sure how to evaluate the HEX to make the decision whether the proximity of the chosen color to black is too close to use black text.

任何想法?

推荐答案

而不是增加RGB分量一起像其他回答者(ricknz)说,你实际上应该把他们的平均水平。

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.

所以,你必须乘红色分量第一次0.299,绿时代0.587和蓝色时代0.114

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

所以亮度由下式给出:亮度=(R * 0.299 + G * 0.587 + B * 0.114)/ 3

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。 256师,因为我们的RGB从0-256(而不是0-1)

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

编辑:改变了calculcation为256分和768不是如此巧妙评论

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

这篇关于评价一个十六进制值是否太暗或太亮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆