根据背景颜色确定字体颜色 [英] Determine font color based on background color
问题描述
给定一个系统(例如一个网站),它允许用户自定义一些部分的背景颜色,但不是字体颜色(以保持选项数量最小),有没有办法以编程方式确定是否 或黑色字体颜色是必需的吗?
Given a system (a website for instance) that lets a user customize the background color for some section but not the font color (to keep number of options to a minimum), is there a way to programmatically determine if a "light" or "dark" font color is necessary?
我确定有一些算法,但我不知道足够的颜色,
I'm sure there is some algorithm, but I don't know enough about colors, luminosity, etc to figure it out on my own.
推荐答案
我遇到了类似的问题。我不得不找到一个很好的选择对比度字体颜色的方法来在颜色尺度/热图上显示文本标签。它必须是通用的方法,生成的颜色必须是好看,这意味着简单生成补色不是好的解决方案 - 有时它产生奇怪,非常强烈的颜色难以观看和阅读。
I encountered similar problem. I had to find a good method of selecting contrastive font color to display text labels on colorscales/heatmaps. It had to be universal method and generated color had to be "good looking", which means that simple generating complementary color was not good solution - sometimes it generated strange, very intensive colors that were hard to watch and read.
经过长时间的测试,并试图解决这个问题,我发现最好的解决方案是选择白色字体为黑颜色,黑色字体为亮颜色。
After long hours of testing and trying to solve this problem, I found out that the best solution is to select white font for "dark" colors, and black font for "bright" colors.
以下是我在C#中使用的函数示例:
Here's an example of function I am using in C#:
Color ContrastColor(Color color)
{
int d = 0;
// Counting the perceptive luminance - human eye favors green color...
double a = 1 - ( 0.299 * color.R + 0.587 * color.G + 0.114 * color.B)/255;
if (a < 0.5)
d = 0; // bright colors - black font
else
d = 255; // dark colors - white font
return Color.FromArgb(d, d, d);
}
此测试适用于许多不同的色彩(彩虹,灰度,和许多其他),是我发现的唯一的通用方法。
This was tested for many various colorscales (rainbow, grayscale, heat, ice, and many others) and is the only "universal" method I found out.
编辑
将计数公式更改为
感知亮度 - 它真的看起来更好!
Edit
Changed the formula of counting a
to "perceptive luminance" - it really looks better! Already implemented it in my software, looks great.
编辑2
@WebSeed提供了这个算法的一个很好的工作示例: a href =http://codepen.io/WebSeed/full/pvgqEq/ =nofollow noreferrer> http://codepen.io/WebSeed/full/pvgqEq/
这篇关于根据背景颜色确定字体颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!