Transparent equivalent of given color

后端 未结 5 1397
温柔的废话
温柔的废话 2020-12-23 19:11

I\'ve had this a few times, so here goes: I\'m making some plots which hold curves with estimates of a parameter given a tuning parameter.

Typically, I also have SDs

5条回答
  •  自闭症患者
    2020-12-23 19:58

    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"
    

提交回复
热议问题