|
4 | 4 | #' @return hexadecimal colour value (if is.na(x), return "transparent" for compatibility with Plotly) |
5 | 5 | #' @export |
6 | 6 | toRGB <- function(x, alpha = 1) { |
| 7 | + if (is.null(x)) return(x) |
7 | 8 | # add alpha to already converted "rgb(x,y,z)" codes |
8 | | - idx <- grepl("^rgb\\(", x) & alpha < 1 & 0 < alpha |
| 9 | + idx <- grepl("^rgba\\(", x) & alpha <= 1 & 0 <= alpha |
9 | 10 | if (any(idx)) { |
10 | | - x[idx] <- sub("^rgb", "rgba", x[idx]) |
11 | | - x[idx] <- paste0(sub("\\)", ",", x[idx]), alpha, ")") |
| 11 | + x[idx] <- rgb2hex(x[idx]) |
12 | 12 | } |
13 | | - # return code if |
14 | | - if (any(is.null(x) || grepl("^rgb[a]?\\(", x))) return(x) |
15 | 13 | # for some reason ggplot2 has "NA" in some place (instead of NA) |
16 | 14 | if (is.character(x)) { |
17 | 15 | x[x == "NA"] <- NA |
18 | 16 | } |
19 | 17 | # as of ggplot2 version 1.1, an NA alpha is treated as though it's 1 |
20 | 18 | alpha[is.na(alpha)] <- 1 |
21 | | - rgb_matrix <- col2rgb(x, alpha = TRUE) |
| 19 | + rgb_matrix <- grDevices::col2rgb(x, alpha = TRUE) |
22 | 20 | # multiply the existing alpha with specified alpha (both on 0-1 scale) |
23 | 21 | rgb_matrix["alpha", ] <- alpha * scales::rescale( |
24 | 22 | rgb_matrix["alpha", ], from = c(0, 255) |
25 | 23 | ) |
26 | | - container <- ifelse(rgb_matrix["alpha", ] == 1, "rgb(%s)", "rgba(%s)") |
27 | | - rgba <- sprintf(container, apply(rgb_matrix, 2, paste, collapse = ",")) |
28 | | - rgba <- sub(",1\\)", ")", rgba) |
| 24 | + rgba <- sprintf("rgba(%s)", apply(rgb_matrix, 2, paste, collapse = ",")) |
29 | 25 | rgba[is.na(x)] <- "transparent" |
30 | 26 | rgba |
31 | 27 | } |
| 28 | + |
| 29 | +# take a 'plotly color' and produce a hex code |
| 30 | +rgb2hex <- function(string = "rgba(255,255,255,1)") { |
| 31 | + vals <- sub("rgba\\(", "", sub("\\)", "", string)) |
| 32 | + valz <- strsplit(vals, ",") |
| 33 | + sapply(valz, function(x) { |
| 34 | + x <- setNames(as.numeric(x), c("red", "green", "blue", "alpha")) |
| 35 | + x[["alpha"]] <- x[["alpha"]] * 255 |
| 36 | + do.call(grDevices::rgb, c(x, list(maxColorValue = 255))) |
| 37 | + }) |
| 38 | +} |
0 commit comments