我想展示一些像这个例子的图片
填充颜色由数据库中颜色为十六进制的字段决定(例如:ClassX -> color: #66FFFF)。 现在,我想显示上面的数据与所选的颜色填充(如上图),但我需要知道如果颜色是暗或光,所以我知道如果文字应该在白色或黑色。 有办法吗?谢谢大家
我想展示一些像这个例子的图片
填充颜色由数据库中颜色为十六进制的字段决定(例如:ClassX -> color: #66FFFF)。 现在,我想显示上面的数据与所选的颜色填充(如上图),但我需要知道如果颜色是暗或光,所以我知道如果文字应该在白色或黑色。 有办法吗?谢谢大家
当前回答
这只是一个示例,它将在单击元素时更改SVG复选标记的颜色。它将根据所单击元素的背景色将复选标记颜色设置为黑色或白色。
checkmarkColor: function(el) {
var self = el;
var contrast = function checkContrast(rgb) {
// @TODO check for HEX value
// Get RGB value between parenthesis, and remove any whitespace
rgb = rgb.split(/\(([^)]+)\)/)[1].replace(/ /g, '');
// map RGB values to variables
var r = parseInt(rgb.split(',')[0], 10),
g = parseInt(rgb.split(',')[1], 10),
b = parseInt(rgb.split(',')[2], 10),
a;
// if RGBA, map alpha to variable (not currently in use)
if (rgb.split(',')[3] !== null) {
a = parseInt(rgb.split(',')[3], 10);
}
// calculate contrast of color (standard grayscale algorithmic formula)
var contrast = (Math.round(r * 299) + Math.round(g * 587) + Math.round(b * 114)) / 1000;
return (contrast >= 128) ? 'black' : 'white';
};
$('#steps .step.color .color-item .icon-ui-checkmark-shadow svg').css({
'fill': contrast($(self).css('background-color'))
});
}
onClickExtColor: function(evt) {
var self = this;
self.checkmarkColor(evt.currentTarget);
}
https://gist.github.com/dcondrey/183971f17808e9277572
其他回答
这个(JavaScript代码)怎么样?
/**
* Get color (black/white) depending on bgColor so it would be clearly seen.
* @param bgColor
* @returns {string}
*/
getColorByBgColor(bgColor) {
if (!bgColor) { return ''; }
return (parseInt(bgColor.replace('#', ''), 16) > 0xffffff / 2) ? '#000' : '#fff';
}
我正在使用tinyColor库,它也可以做这项工作。
import { TinyColor } from '@ctrl/tinycolor'
// ...
getColorContrast(color = '#66FFFF'): string {
if(new TinyColor(color).getLuminance() > 0.179) { // 0.179 -> Mark Ransom answer
return '#000'
} else {
return '#fff'
}
}
此方法也接受rgb颜色,如rgb(102,255,255)
我从来没有做过这样的事情,但是写一个函数来检查每个颜色的值与十六进制7F (FF / 2)的中位数颜色。如果三种颜色中有两种大于7F,那么你正在使用较深的颜色。
当使用androidx. composer .ui.graphics. color时,接受的答案在Android上从未工作过。然后我发现在Android Jetpack Compose中实际上有内置的luminance()函数,该函数返回[0,1]之间的亮度值。文档说明:“基于WCAG 2.0中定义的相对亮度公式,W3C推荐标准2008年12月11日。”
以下是官方源代码。
使用示例:
fun Color.generateOnColor()
: Color {
return if (luminance() > 0.5f) {
Color.Black.copy(alpha = .8f)
} else {
Color.White
}
}
@SoBiT,我在看你的答案,看起来不错,但有一个小错误。你的函数hexToG和hextoB需要一个小的编辑。substr中的最后一个数字是字符串的长度,所以在这种情况下,它应该是“2”,而不是4或6。
function hexToR($h) {
return hexdec(substr(cutHex($h), 0, 2));
}
function hexToG($h) {
return hexdec(substr(cutHex($h), 2, 2));
}
function hexToB($h) {
return hexdec(substr(cutHex($h), 4, 2));
}