ソースを参照

Factor light-dark color test out of choose_dark_or_light()

tags/v0.3.0
コミット
bfea283b54
2個のファイルの変更11行の追加8行の削除
  1. +9
    -6
      R/utils.R
  2. +2
    -2
      man/choose_dark_or_light.Rd

+ 9
- 6
R/utils.R ファイルの表示

#' best contrast. Follows W3C Recommendations. #' best contrast. Follows W3C Recommendations.
#' #'
#' @references <https://stackoverflow.com/a/3943023/2022615> #' @references <https://stackoverflow.com/a/3943023/2022615>
#' @param x The background color
#' @param x The background color (hex)
#' @param black Text or foreground color, e.g. "#222" or #' @param black Text or foreground color, e.g. "#222" or
#' `substitute(darken_color(x, 0.8))`, if black text provides the best contrast. #' `substitute(darken_color(x, 0.8))`, if black text provides the best contrast.
#' @param white Text or foreground color or expression, e.g. "#EEE" or #' @param white Text or foreground color or expression, e.g. "#EEE" or
#' `substitute(lighten_color(x, 0.8))`, if white text provides the best contrast. #' `substitute(lighten_color(x, 0.8))`, if white text provides the best contrast.
#' @export #' @export
choose_dark_or_light <- function(x, black = "#000", white = "#FFF") {
# x = color_hex
# black <- substitute(black)
# white <- substitute(white)
choose_dark_or_light <- function(x, black = "#000000", white = "#FFFFFF") {
if (is_light_color(x)) eval(black) else eval(white)
}

is_light_color <- function(x) {
# this function returns TRUE if the given color
# is light-colored and requires dark text
color_rgb <- col2rgb(x)[, 1] color_rgb <- col2rgb(x)[, 1]
# from https://stackoverflow.com/a/3943023/2022615 # from https://stackoverflow.com/a/3943023/2022615
color_rgb <- color_rgb / 255 color_rgb <- color_rgb / 255
color_rgb[color_rgb <= 0.03928] <- color_rgb[color_rgb <= 0.03928]/12.92 color_rgb[color_rgb <= 0.03928] <- color_rgb[color_rgb <= 0.03928]/12.92
color_rgb[color_rgb > 0.03928] <- ((color_rgb[color_rgb > 0.03928] + 0.055)/1.055)^2.4 color_rgb[color_rgb > 0.03928] <- ((color_rgb[color_rgb > 0.03928] + 0.055)/1.055)^2.4
lum <- t(c(0.2126, 0.7152, 0.0722)) %*% color_rgb lum <- t(c(0.2126, 0.7152, 0.0722)) %*% color_rgb
if (lum[1, 1] > 0.179) eval(black) else eval(white)
lum[1, 1] > 0.179
} }


#' @keywords internal #' @keywords internal

+ 2
- 2
man/choose_dark_or_light.Rd ファイルの表示

\alias{choose_dark_or_light} \alias{choose_dark_or_light}
\title{Choose dark or light color} \title{Choose dark or light color}
\usage{ \usage{
choose_dark_or_light(x, black = "#000", white = "#FFF")
choose_dark_or_light(x, black = "#000000", white = "#FFFFFF")
} }
\arguments{ \arguments{
\item{x}{The background color}
\item{x}{The background color (hex)}


\item{black}{Text or foreground color, e.g. "#222" or \item{black}{Text or foreground color, e.g. "#222" or
\code{substitute(darken_color(x, 0.8))}, if black text provides the best contrast.} \code{substitute(darken_color(x, 0.8))}, if black text provides the best contrast.}

読み込み中…
キャンセル
保存