|
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) |
8 | | - # as of ggplot2 version 1.1, an NA alpha is treated as though it's 1 |
9 | | - alpha[is.na(alpha)] <- 1 |
10 | | - # if we've already made the proper conversion, return the input |
11 | | - if (inherits(x, "plotly_rgba")) return(x) |
12 | | - if (inherits(x, "plotly_rgb")) { |
13 | | - if (all(alpha == 1)) return(x) |
14 | | - # all alpha channel |
15 | | - x <- sub("^rgb", "rgba", sub("\\)", paste0(",", alpha, ")"), x)) |
16 | | - return(prefix_class(x, "plotly_rgba")) |
| 7 | + # add alpha to already converted "rgb(x,y,z)" codes |
| 8 | + idx <- grepl("^rgb\\(", x) & alpha < 1 & 0 < alpha |
| 9 | + if (any(idx)) { |
| 10 | + x[idx] <- sub("^rgb", "rgba", x[idx]) |
| 11 | + x[idx] <- paste0(sub("\\)", ",", x[idx]), alpha, ")") |
17 | 12 | } |
| 13 | + # return code if |
| 14 | + if (any(is.null(x) || grepl("^rgb[a]?\\(", x))) return(x) |
18 | 15 | # for some reason ggplot2 has "NA" in some place (instead of NA) |
19 | 16 | if (is.character(x)) { |
20 | 17 | x[x == "NA"] <- NA |
21 | 18 | } |
22 | | - has_alpha <- all(0 <= alpha & alpha < 1) |
23 | | - rgb_matrix <- col2rgb(x, alpha = has_alpha) |
24 | | - # rescale alpha |
25 | | - # TODO: what if x already has an alpha channel??? |
26 | | - if (has_alpha) rgb_matrix["alpha", ] <- alpha |
27 | | - container <- if (has_alpha) "rgba(%s)" else "rgb(%s)" |
28 | | - rgb_a <- sprintf(container, apply(rgb_matrix, 2, paste, collapse = ",")) |
29 | | - rgb_a[is.na(x)] <- "transparent" |
30 | | - structure(rgb_a, class = if (has_alpha) "plotly_rgba" else "plotly_rgb") |
| 19 | + # as of ggplot2 version 1.1, an NA alpha is treated as though it's 1 |
| 20 | + alpha[is.na(alpha)] <- 1 |
| 21 | + rgb_matrix <- col2rgb(x, alpha = TRUE) |
| 22 | + # multiply the existing alpha with specified alpha (both on 0-1 scale) |
| 23 | + rgb_matrix["alpha", ] <- alpha * scales::rescale( |
| 24 | + rgb_matrix["alpha", ], from = c(0, 255) |
| 25 | + ) |
| 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) |
| 29 | + rgba[is.na(x)] <- "transparent" |
| 30 | + rgba |
31 | 31 | } |
0 commit comments