找出十六进制颜色是深色还是浅色 [英] Finding out if a Hex color is dark or light

查看:229
本文介绍了找出十六进制颜色是深色还是浅色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#,我想确定十六进制颜色(网络格式,例如:#FF2233)是深色还是浅色,我可以根据这些颜色决定前一种颜色(字体颜色)应该是.

Using C# I'd like to find out if a Hex color (web format, e.g: #FF2233) is dark or light based on which I can decide what the fore color (font color) should be.

应用程序的用户选择颜色作为某些元素的背景. 然后,程序需要确定用户的背景色是否为深色,然后选择白色作为字体颜色(以获得最佳的可读性和对比度),否则选择黑色.

The color is selected by application's users as background of certain elements. The program then needs to figure out if the user's background color is dark then choose white as the font color (for best readability and contrast) otherwise black is chosen.

到目前为止,我一直在尝试计算"F","E","C","D","B"和"A"的出现次数.如果至少出现4次,我认为颜色是明亮的.它的工作时间约为70%.

So far I have been trying to count the number of occurrences of the "F","E","C","D","B" and "A". If there are at least 4 occurrences I consider the color bright. It works for about 70% of times.

是否有更好的解决方案?

Is there a better solution for this?

推荐答案

如果转换

What if you convert your Hex color to rgb format then you make the summ of red green and blue if it's over ((255*3)/2) it's a dark color, else it's light color

        System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FF2233");
        if (col.R * 0.2126 + col.G * 0.7152 + col.B * 0.0722 > 255 / 2)
        {
            //dark color
        }
        else
        {
            //light color
        }

由于@Jon的想法,因此更新了亮度

Updated with Luminance, thanks to @Jon idea

这篇关于找出十六进制颜色是深色还是浅色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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