Debian Codegraph @

R/adjust_transparency.R

raw
1 #' Adjust or Extract Transparency of Colors
2 #'
3 #' Adjust (i.e., add, remove, or modify) or extract alpha transparency of a vector of colors.
4 #'
5 #' Alpha transparency is useful for making colors semi-transparent, e.g., for
6 #' overlaying different elements in graphics. An alpha value of 0 (or 00 in hex strings)
7 #' corresponds to fully transparent and an alpha value of 1 (or FF in hex strings)
8 #' corresponds to fully opaque. If a color hex string in R does not provide an explicit
9 #' alpha transparency, the color is assumed to be fully opaque.
10 #'
11 #' The \code{adjust_transparency} function can be used to adjust the alpha transparency
12 #' of a set of colors. It always returns a hex color specification. This hex color
13 #' can have the alpha transparency added/removed/modified depending on the
14 #' specification of \code{alpha}: \itemize{
15 #' \item \code{alpha = NULL}: Returns a hex vector with alpha transparency only if needed.
16 #' Thus, it keeps the alpha transparency for the colors (if any) but only if
17 #' different from opaque.
18 #' \item \code{alpha = TRUE}: Returns a hex vector with alpha transparency
19 #' for all colors, using opaque (FF) as the default if missing.
20 #' \item \code{alpha = FALSE}: Returns a hex vector without alpha transparency for
21 #' all colors (even if the original colors had non-opaque alpha).
22 #' \item \code{alpha} numeric: Returns a hex vector with alpha transparency for
23 #' all colors set to the \code{alpha} argument (recycled if necessary).
24 #' }
25 #'
26 #' The \code{extract_transparency} function can be used to extract the alpha transparency
27 #' from a set of colors. It allows to specify the \code{default} value - that should be used
28 #' for colors without an explicit alpha transparency (defaulting to fully opaque) - and
29 #' \code{mode} of the return value. This can either be numeric (in [0, 1]), integer
30 #' (0L, 1L, \dots, 255L), character (\dQuote{00}, \dQuote{01}, \dots, \dQuote{FF}),
31 #' or an object of class \code{\link[base]{hexmode}} (internally represented as integer
32 #' with printing as character). The \code{default} can use any of these modes as well
33 #' (independent of the output \code{mode}) or be \code{NA}.
34 #'
35 #' @param col vector of R colors. Can be any of the three kinds of R colors,
36 #' i.e., either a color name (an element of
37 #' \code{\link[grDevices]{colors}}), a hexadecimal (hex) string of the form
38 #' \code{"#rrggbb"} or \code{"#rrggbbaa"} (see \code{\link[grDevices]{rgb}}), or
39 #' an integer \code{i} meaning \code{palette()[i]}. Additionally, \code{col} can be
40 #' a formal \code{\link[colorspace]{color-class}} object or a matrix with three
41 #' rows containing R/G/B (0-255) values.
42 #' @param alpha either a new alpha transparency value or logical (to add/remove alpha)
43 #' or \code{NULL}. See details.
44 #' @param mode character specifying the output mode for the alpha transparency, can be
45 #' \code{"numeric"}, \code{"integer"}, \code{"character"} or \code{"hexmode"}. See details.
46 #' @param default vector of length 1 specifying the default alpha transparency that should
47 #' be returned for colors that do not specify any explicitly (defaulting to fully opaque).
48 #' Can either be numeric, integer, character, or hexmode.
49 #' @return For \code{adjust_transparency} character vector with hexadecimal color strings with alpha transparency
50 #' corresponding to \code{alpha} argument. For \code{extract_transparency} a vector of
51 #' alpha transparency values with the indicated \code{mode}.
52 #' @seealso \code{\link[grDevices]{rgb}}, \code{\link[colorspace]{desaturate}}, \code{\link[colorspace]{lighten}}
53 #' @references Zeileis A, Fisher JC, Hornik K, Ihaka R, McWhite CD, Murrell P, Stauffer R, Wilke CO (2020).
54 #' \dQuote{colorspace: A Toolbox for Manipulating and Assessing Colors and Palettes.}
55 #' \emph{Journal of Statistical Software}, \bold{96}(1), 1--49. \doi{10.18637/jss.v096.i01}
56 #' @keywords color
57 #' @examples
58 #' ## modify transparency of a color (in different formats)
59 #' adjust_transparency("black", alpha = c(0, 0.5, 1)) ## name
60 #' adjust_transparency("#000000", alpha = c(0, 0.5, 1)) ## hex string
61 #' adjust_transparency(1, alpha = c(0, 0.5, 1)) ## palette() integer
62 #'
63 #' ## three shades of gray (in different formats:
64 #' ## name/opaque, hex/opaque, hex/semi-transparent)
65 #' x <- c("gray", "#BEBEBE", "#BEBEBE80")
66 #'
67 #' ## adjust transparency
68 #' adjust_transparency(x, alpha = NULL) ## only if necessary
69 #' adjust_transparency(x, alpha = TRUE) ## add
70 #' adjust_transparency(x, alpha = FALSE) ## remove
71 #' adjust_transparency(x, alpha = 0.8) ## modify
72 #'
73 #' ## extract transparency in different formats
74 #' extract_transparency(x, mode = "numeric") ## default
75 #' extract_transparency(x, mode = "integer")
76 #' extract_transparency(x, mode = "character")
77 #' extract_transparency(x, mode = "hexmode")
78 #'
79 #' ## extract transparency with different default values
80 #' extract_transparency(x, default = NA)
81 #' extract_transparency(x, default = 0.5)
82 #' extract_transparency(x, default = 128L)
83 #' extract_transparency(x, default = "80", mode = "integer")
84 #' @export adjust_transparency
85 #' @importFrom grDevices rgb col2rgb
86 #' @importFrom stats setNames
87
88 adjust_transparency <- function(col, alpha = TRUE) {
89
90 ## alpha argument controls new alpha values
91 new_alpha <- alpha
92 if(inherits(new_alpha, "hexmode")) new_alpha <- unclass(new_alpha)
93
94 ## support S4 color specifications as well (with default alpha = 1)
95 if(inherits(col, "color")) {
96 col <- hex(col)
97 col[] <- paste0(col[], "FF")
98 }
99
100 ## keep indizes of NA colors
101 NAidx <- which(is.na(col))
102 n <- if(is.matrix(col) && is.numeric(col)) NCOL(col) else length(col)
103
104 ## handle prismatic colors class (essentially character + class attribute)
105 if(is.character(col) && inherits(col, "colors")) {
106 col <- as.character(col) ## workaround for prismatic colors class
107 prismatic <- TRUE
108 } else {
109 prismatic <- FALSE
110 }
111
112 ## col has to be hex code, otherwise col2rgb is used
113 if(is.character(col) &&
114 (all(substr(col, 1L, 1L) == "#") & all(nchar(col) %in% c(7L, 9L))))
115 {
116 ## extract alpha from hex (if any)
117 alpha <- substr(col, 8L, 9L)
118 ## retain only RGB in hex
119 col <- setNames(substr(col, 1L, 7L), names(col))
120 } else {
121 if(!(is.matrix(col) && is.numeric(col))) col <- col2rgb(col, alpha = TRUE)
122 ## extract alpha values (if any)
123 alpha <- if(NROW(col) > 3L) convert_transparency(col[4L, ]/255, mode = "character") else rep.int("FF", n)
124 ## retain only RGB
125 col <- rgb(t(col[1L:3L, , drop = FALSE]), maxColorValue = 255, names = colnames(col))
126 }
127
128 ## adjust alpha transparency
129 if(is.null(new_alpha)) {
130 alpha[alpha == "FF"] <- ""
131 } else if(identical(new_alpha, FALSE)) {
132 alpha <- rep.int("", n)
133 } else if(identical(new_alpha, TRUE)) {
134 alpha[alpha == ""] <- "FF"
135 } else {
136 alpha <- convert_transparency(new_alpha, mode = "character")
137 if(length(alpha) != n) {
138 n <- max(n, length(alpha))
139 if(length(col) != n) col <- rep_len(col, n)
140 if(length(alpha) != n) alpha <- rep_len(alpha, n)
141 }
142 }
143
144 ## add alpha again (if any) and manage NAs
145 col[] <- paste(col[], alpha, sep = "")
146 if(length(NAidx) > 0) col[NAidx] <- NA
147
148 ## add prismatic colors class again (if applicable)
149 if(prismatic) attr(col, "class") <- "colors"
150
151 return(col)
152 }
153
154 #' @rdname adjust_transparency
155 #' @export extract_transparency
156 extract_transparency <- function(col, mode = "numeric", default = 1) {
157
158 ## handle mode of return value
159 mode <- match.arg(mode, c("numeric", "double", "integer", "character", "hexmode"))
160 if(mode == "double") mode <- "numeric"
161
162 ## handle default
163 if(length(default) > 1L) {
164 warning("'default' should be of length 1, first element used")
165 default <- default[1L]
166 } else if(length(default) < 1L) {
167 default <- NA
168 }
169 if(inherits(default, "hexmode")) default <- unclass(default)
170 if(mode == "hexmode") {
171 hexmode <- TRUE
172 mode <- "integer"
173 } else {
174 hexmode <- FALSE
175 }
176 na <- switch(mode,
177 "numeric" = NA_real_,
178 "character" = NA_character_,
179 NA_integer_)
180 if(is.na(default)) {
181 default <- na
182 } else if(is.character(default) | is.numeric(default)) {
183 default <- convert_transparency(default, mode = mode)
184 } else {
185 warning("unknown type of 'default' using NA instead")
186 default <- na
187 }
188
189 ## for S4 color specifications or RGB matrices the default is used
190 if(inherits(col, "color")) col <- coords(col)
191
192 ## number of colors and position of NA colors
193 if(is.matrix(col) && is.numeric(col)) {
194 n <- NCOL(col)
195 ina <- which(apply(is.na(col), 1L, any))
196 } else {
197 n <- length(col)
198 ina <- which(is.na(col))
199 }
200
201 ## cases where alpha can be extracted
202 ialpha <- if(is.character(col)) {
203 which(substr(col, 1L, 1L) == "#" & nchar(col) == 9L)
204 } else {
205 integer(0)
206 }
207
208 ## set up return value
209 alpha <- rep.int(default, n)
210 if(length(ialpha) > 0L) alpha[ialpha] <- convert_transparency(substr(col[ialpha], 8L, 9L), mode = mode)
211 alpha[ina] <- na
212 if(hexmode) alpha <- structure(alpha, class = "hexmode")
213 return(alpha)
214 }
215
216 ## auxiliary function
217 convert_transparency <- function(x, mode = "numeric") {
218 mode <- match.arg(mode, c("numeric", "integer", "character"))
219 if(is.character(x)) {
220 if(!all(toupper(x) %in% format(as.hexmode(0L:255L), width = 2L, upper.case = TRUE))) {
221 stop("invalid character specification of alpha transparency, must be in 00, 01, ..., FF")
222 }
223 x <- switch(mode,
224 "integer" = as.integer(as.hexmode(x)),
225 "numeric" = as.integer(as.hexmode(x))/255,
226 x)
227 } else if(is.integer(x)) {
228 if(!all(x %in% 0L:255L)) {
229 stop("invalid integer specification of alpha transparency, must be in 0L, 1L, ..., 255L")
230 }
231 x <- switch(mode,
232 "numeric" = x/255,
233 "character" = format(as.hexmode(x), width = 2L, upper.case = TRUE),
234 x)
235 } else if(is.numeric(x)) {
236 if(!all(x >= 0 & x <= 1)) {
237 stop("invalid numeric specification of alpha transparency, must be in [0, 1]")
238 }
239 x <- switch(mode,
240 "integer" = as.integer(round(x * 255 + 0.0001)),
241 "character" = format(as.hexmode(round(x * 255 + 0.0001)), width = 2L, upper.case = TRUE),
242 x)
243 }
244 return(x)
245 }
246