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.
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
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"
Implemented as a function:
isDark <- function(colr) { (sum( col2rgb(colr) * c(299, 587,114))/1000 < 123) }
isDark("red")
[1] TRUE
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…