标签和背景之间的对比:确定颜色是浅色还是深色 [英] Contrast between label and background: determine if color is light or dark

查看:60
本文介绍了标签和背景之间的对比:确定颜色是浅色还是深色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有白色标签的条形图.有时背景颜色太浅,白色标签变得难以辨认.我正在寻找一个接受颜色值并返回颜色是深色还是浅色的函数.然后,我可以将标签颜色相应地设置为白色或黑色,以获得与背景的最佳对比度.

I have a barplot with labels in white. Sometimes the color of background is too light and the white label becomes illegible. I'm looking for a function that takes a color value and returns whether the color is dark or light. Then I can set the label color to white or black accordingly to obtain the best contrast against the background.

推荐答案

这是一种根据@MrFlick提供的(第二个)链接中的强度等级来选择黑与白文本颜色的策略.

Here's a strategy to implement picking a text color of black vs white based on the intensity scale in the (second) link provided by @MrFlick.

博客引用了W3C出版物:用于计算广告素材的感知亮度的标准公式颜色,该算法使用了RGB编码颜色的算法:

The blog cited a W3C publication: a standard formula for calculating the perceived brightness of a color that used an algorithm for RGB encoded colors:

 ((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000

col2rgb 函数提供了3行矩阵,我将其乘以该网页中提供的因子.我以红色"为背景色为例,然后选择的文本为白色"

The col2rgb function delivers a 3-row matrix which I multiply by the factors offered in that webpage. I used an example of "red" as a background color and the chosen text would then be "white"

 c( "black", "white")[  1+(sum( col2rgb("red") *c(299, 587,114))/1000 < 123) ]
[1] "white"

作为功能实现:

isDark <- function(colr) { (sum( col2rgb(colr) * c(299, 587,114))/1000 < 123) }
isDark("red")
[1] TRUE

这篇关于标签和背景之间的对比:确定颜色是浅色还是深色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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