Transparent equivalent of given color

青春壹個敷衍的年華 提交于 2019-11-29 22:48:36

Have you had a look at ?rgb?

Usage:

rgb(red, green, blue, alpha, names = NULL, maxColorValue = 1)

An alpha transparency value can also be specified (as an opacity, so ‘0’ means fully transparent and ‘max’ means opaque). If alpha’ is not specified, an opaque colour is generated.

The alpha parameter is for specifying transparency. col2rgb splits R colors specified in other ways into RGB so you can feed them to rgb.

There is a function adjustcolor in grDevices package, that works like this in your case:

    adjustcolor( "red", alpha.f = 0.2)

I think is more common to specify alpha in [0,1]. This function do that, plus accept several colors as arguments:

makeTransparent = function(..., alpha=0.5) {

  if(alpha<0 | alpha>1) stop("alpha must be between 0 and 1")

  alpha = floor(255*alpha)  
  newColor = col2rgb(col=unlist(list(...)), alpha=FALSE)

  .makeTransparent = function(col, alpha) {
    rgb(red=col[1], green=col[2], blue=col[3], alpha=alpha, maxColorValue=255)
  }

  newColor = apply(newColor, 2, .makeTransparent, alpha=alpha)

  return(newColor)

}

And, to test:

makeTransparent(2, 4)
[1] "#FF00007F" "#0000FF7F"
makeTransparent("red", "blue")
[1] "#FF00007F" "#0000FF7F"
makeTransparent(rgb(1,0,0), rgb(0,0,1))
[1] "#FF00007F" "#0000FF7F"

makeTransparent("red", "blue", alpha=0.8)
[1] "#FF0000CC" "#0000FFCC"

Converting valuable comment to answer:

Use alpha from package scales - first argument is colour, second alpha (in 0-1 range).

Or write function overt it:

makeTransparent <- function(someColor, alpha=100) scales::alpha(someColor, alpha/100)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!