Home > Enterprise >  remove transparency from grey but keep grey itself
remove transparency from grey but keep grey itself

Time:11-27

I recently learned how to remove transparency from a color but keep the color itself:

library(scales)


# approach for colors
show_col("green")


# make light transparent green
alpha("green",0.3) -> transparent_green

# keep the light green but remove transparency
ch <- rgb2hsv(col2rgb(transparent_green))
nontransparent_green <- hsv(h=ch["h",], v=ch["v",], s=0.3)

#compare greens
show_col(c(transparent_green,nontransparent_green))

Created on 2022-11-26 with reprex v2.0.2

however, this does not work for greys:

library(scales)

# aprroach for grey
show_col("grey10")


# make light transparent grey
alpha("grey10",0.3) -> transparent_grey

# keep the light grey but remove transparency
ch <- rgb2hsv(col2rgb(transparent_grey))
nontransparent_grey <- hsv(h=ch["h",], v=ch["v",], s=0.3)

#compare greys
show_col(c(transparent_grey,nontransparent_grey))

Created on 2022-11-26 with reprex v2.0.2

CodePudding user response:

You could try this little function which should work irrespective of the starting colour.

de_alpha <- function(col) {
  col <- col2rgb(col, alpha = TRUE)
  alpha <- col[4,]
  col <- col[1:3,]
  whiteness <- (255 - alpha)/255
  do.call(rgb, as.list((col   (255 - col) * whiteness)/255))
}

This works on green giving the same result:

transparent_green    <- scales::alpha("green", 0.3)
nontransparent_green <- de_alpha(transparent_green)

scales::show_col(c(transparent_green, nontransparent_green))

But also works on your grey example:

transparent_grey    <- scales::alpha("grey10", 0.3)
nontransparent_grey <- de_alpha(transparent_grey)

scales::show_col(c(transparent_grey, nontransparent_grey))

Created on 2022-11-26 with reprex v2.0.2

  • Related