给定一个系统(例如一个网站),允许用户自定义某些部分的背景色,但不允许自定义字体颜色(以保持选项的数量最小化),是否有一种方法可以通过编程来确定“浅色”或“深色”字体颜色是必要的?

我相信有一些算法,但我对颜色、光度等了解不够,无法自己找出答案。


当前回答

作为Kotlin / Android扩展:

fun Int.getContrastColor(): Int {
    // Counting the perceptive luminance - human eye favors green color...
    val a = 1 - (0.299 * Color.red(this) + 0.587 * Color.green(this) + 0.114 * Color.blue(this)) / 255
    return if (a < 0.5) Color.BLACK else Color.WHITE
}

其他回答

iOS Swift 3.0 (UIColor扩展):

func isLight() -> Bool
{
    if let components = self.cgColor.components, let firstComponentValue = components[0], let secondComponentValue = components[1], let thirdComponentValue = components[2] {
        let firstComponent = (firstComponentValue * 299)
        let secondComponent = (secondComponentValue * 587)
        let thirdComponent = (thirdComponentValue * 114)
        let brightness = (firstComponent + secondComponent + thirdComponent) / 1000

        if brightness < 0.5
        {
            return false
        }else{
            return true
        }
    }  

    print("Unable to grab components and determine brightness")
    return nil
}

如果你是为了视觉效果而操纵色彩空间,通常使用HSL(色相、饱和度和明度)比RGB更容易。在RGB中移动颜色以获得自然的令人愉悦的效果在概念上是相当困难的,而转换为HSL,在那里进行操作,然后再转换回来在概念上更直观,并且总是会给出更好的外观结果。

维基百科对HSL和密切相关的HSV有很好的介绍。网络上有免费的代码可以进行转换(例如这里是一个javascript实现)

你使用什么精确的转换是一个品味问题,但我个人认为颠倒色调和明度组件肯定会产生一个良好的高对比度的颜色作为第一个近似,但你可以很容易地追求更微妙的效果。

基于R版本的@Gacek的答案来获得亮度(你可以很容易地应用你自己的阈值)

# vectorized
luminance = function(col) c(c(.299, .587, .114) %*% col2rgb(col)/255)

用法:

luminance(c('black', 'white', '#236FAB', 'darkred', '#01F11F'))
# [1] 0.0000000 1.0000000 0.3730039 0.1629843 0.5698039

objective-c的实现

+ (UIColor*) getContrastColor:(UIColor*) color {
    CGFloat red, green, blue, alpha;
    [color getRed:&red green:&green blue:&blue alpha:&alpha];
    double a = ( 0.299 * red + 0.587 * green + 0.114 * blue);
    return (a > 0.5) ? [[UIColor alloc]initWithRed:0 green:0 blue:0 alpha:1] : [[UIColor alloc]initWithRed:255 green:255 blue:255 alpha:1];
}

丑陋的Python,如果你不想写它:)

'''
Input a string without hash sign of RGB hex digits to compute
complementary contrasting color such as for fonts
'''
def contrasting_text_color(hex_str):
    (r, g, b) = (hex_str[:2], hex_str[2:4], hex_str[4:])
    return '000' if 1 - (int(r, 16) * 0.299 + int(g, 16) * 0.587 + int(b, 16) * 0.114) / 255 < 0.5 else 'fff'