Created
September 14, 2018 11:51
-
-
Save timriffe/c38e1cbe6e20b09f5c4ca05dc4844327 to your computer and use it in GitHub Desktop.
What is the [0,1] equivalent gray value of a given hex color
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I use this frequently enough .... helps | |
# with determining text value on top of given background color | |
to.greyvalue <- function(hexcolor, method = c("luminosity","average","lightness")[1]){ | |
# https://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/ | |
stopifnot(length(hexcolor) == 1) | |
rgbspec <- as.vector(col2rgb(hexcolor)) / 255 | |
if (method == "luminosity"){ | |
grayval <- sum(c(0.21, 0.72, 0.07) * rgbspec) | |
} | |
if (method == "average"){ | |
grayval <- mean(rgbspec) | |
} | |
if (method == "lightness"){ | |
grayval <- (max(rgbspec) + min(rgbspec)) / 2 | |
} | |
grayval | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment