0

I create two colours as follows:

red  <- rgb(140, 35, 35, alpha=255, max=255)
blue <- rgb(35, 35, 140, alpha=0.6*255, max=255)

How do I create a new colour which is obtained by overlapping the "transparent" blue over the red?

I saw this answer but (a) I don't know how to apply it to an rgb object and (b) I was hoping there is a built-in way to do it.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783

3 Answers3

1

I don't know of a built in way but you could just break the character string back into the original components - strtoi(x = substr(red,2,3), base = 16) + ...

TheComeOnMan
  • 12,535
  • 8
  • 39
  • 54
0

I don't know if there is a built-in way. I'm assuming you want some sort of "blend" (i.e. a weighted average, possibly using the methods in the page you linked to) rather than a "sum" , since the addition There was a similar question on r-help where the the more color-savvy people pointed out that there are other colorspaces where blending colors deliver more sensible results. The method that Duncan Murdoch suggested was to convert to hsv-colorspace and let colorRampPalette do the "averaging" by picking the mid-point of line drawn across the location of those two "points":

# Average the 1st two by taking the middle colour of a 3 colour palette
x <- colorRampPalette(c(red,blue), space = "Lab")(3)[2]
x
[1] "#6C1F57"
> red
[1] "#8C2323FF"
> blue
[1] "#23238C99"

Since that only returns a three color value and no alpha, you may want to handle that separately. I'm not a color-knowledgeable useR so I cannot advise on that matter.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
0

Based on TheComeOnMan answer, I came up with this little function that seems to do what I need:

overlap <- function(under, over) {
  r1 <- strtoi(substr(under, 2, 3), base = 16)
  r2 <- strtoi(substr(over, 2, 3), base = 16)
  g1 <- strtoi(substr(under, 4, 5), base = 16)
  g2 <- strtoi(substr(over, 4, 5), base = 16)
  b1 <- strtoi(substr(under, 6, 7), base = 16)
  b2 <- strtoi(substr(over, 6, 7), base = 16)
  a  <- strtoi(substr(over, 8, 9), base = 16) / 255 # alpha

  result <- rgb(a * r2 + (1 - a) * r1,
                a * g2 + (1 - a) * g1,
                a * b2 + (1 - a) * b1,
                alpha = 255,
                max=255)
  return(result)
}
Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
  • It seems, also, that you could replace `strtoi`s with `col2rgb(c(red, blue), TRUE)` and continue from there – alexis_laz Apr 20 '16 at 08:16