Skip to content

Commit d64d757

Browse files
committed
always use col2rgb(..., alpha=T) to respect hex code with alpha channel
1 parent 2748789 commit d64d757

File tree

1 file changed

+19
-19
lines changed

1 file changed

+19
-19
lines changed

R/toRGB.R

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,28 @@
44
#' @return hexadecimal colour value (if is.na(x), return "transparent" for compatibility with Plotly)
55
#' @export
66
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, ")")
1712
}
13+
# return code if
14+
if (any(is.null(x) || grepl("^rgb[a]?\\(", x))) return(x)
1815
# for some reason ggplot2 has "NA" in some place (instead of NA)
1916
if (is.character(x)) {
2017
x[x == "NA"] <- NA
2118
}
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
3131
}

0 commit comments

Comments
 (0)