Skip to content

Instantly share code, notes, and snippets.

@timriffe
Created September 14, 2018 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timriffe/c38e1cbe6e20b09f5c4ca05dc4844327 to your computer and use it in GitHub Desktop.
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
# 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