我想展示一些像这个例子的图片
填充颜色由数据库中颜色为十六进制的字段决定(例如:ClassX -> color: #66FFFF)。 现在,我想显示上面的数据与所选的颜色填充(如上图),但我需要知道如果颜色是暗或光,所以我知道如果文字应该在白色或黑色。 有办法吗?谢谢大家
我想展示一些像这个例子的图片
填充颜色由数据库中颜色为十六进制的字段决定(例如:ClassX -> color: #66FFFF)。 现在,我想显示上面的数据与所选的颜色填充(如上图),但我需要知道如果颜色是暗或光,所以我知道如果文字应该在白色或黑色。 有办法吗?谢谢大家
当前回答
我正在使用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)
其他回答
以下是我用Java编写的Android解决方案:
// Put this method in whichever class you deem appropriate
// static or non-static, up to you.
public static int getContrastColor(int colorIntValue) {
int red = Color.red(colorIntValue);
int green = Color.green(colorIntValue);
int blue = Color.blue(colorIntValue);
double lum = (((0.299 * red) + ((0.587 * green) + (0.114 * blue))));
return lum > 186 ? 0xFF000000 : 0xFFFFFFFF;
}
// Usage
// If Color is represented as HEX code:
String colorHex = "#484588";
int color = Color.parseColor(colorHex);
// Or if color is Integer:
int color = 0xFF484588;
// Get White (0xFFFFFFFF) or Black (0xFF000000)
int contrastColor = WhateverClass.getContrastColor(color);
基于Mark回答的iOS Objective-c版本代码:
- (UIColor *)contrastForegroundColor {
CGFloat red = 0, green = 0, blue = 0, alpha = 0;
[self getRed:&red green:&green blue:&blue alpha:&alpha];
NSArray<NSNumber *> *rgbArray = @[@(red), @(green), @(blue)];
NSMutableArray<NSNumber *> *parsedRGBArray = [NSMutableArray arrayWithCapacity:rgbArray.count];
for (NSNumber *item in rgbArray) {
if (item.doubleValue <= 0.03928) {
[parsedRGBArray addObject:@(item.doubleValue / 12.92)];
} else {
double newValue = pow((item.doubleValue + 0.055) / 1.055, 2.4);
[parsedRGBArray addObject:@(newValue)];
}
}
double luminance = 0.2126 * parsedRGBArray[0].doubleValue + 0.7152 * parsedRGBArray[1].doubleValue + 0.0722 * parsedRGBArray[2].doubleValue;
return luminance > 0.179 ? UIColor.blackColor : UIColor.whiteColor;
}
我正在使用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,那么你正在使用较深的颜色。
LESS有一个很好的对比度()函数,对我来说效果很好,请参阅http://lesscss.org/functions/#color-operations-contrast
“在两种颜色中选择一种颜色与另一种颜色形成最大的对比。 这对于确保颜色在背景下是可读的很有用,这对于可访问性遵从也很有用。此函数的工作方式与Compass for SASS中的对比函数相同。根据WCAG 2.0,颜色是用伽马校正的亮度值来比较的,而不是它们的亮度。”
例子:
p {
a: contrast(#bbbbbb);
b: contrast(#222222, #101010);
c: contrast(#222222, #101010, #dddddd);
d: contrast(hsl(90, 100%, 50%), #000000, #ffffff, 30%);
e: contrast(hsl(90, 100%, 50%), #000000, #ffffff, 80%);
}
输出:
p {
a: #000000 // black
b: #ffffff // white
c: #dddddd
d: #000000 // black
e: #ffffff // white
}