I have a RGB color in the range of 0.0 to 1.0 for each fragment, I need an algorithm to get the inverse of the color, any ideas how can I do this?
Asked
Active
Viewed 2.6k times
2 Answers
38
newR = 1.0 - r
newG = 1.0 - g
newB = 1.0 - b
If the color has a premultiplied Alpha value use the alpha instead of 1.0:
newR = a - r
newG = a - g
newB = a - b

Mark Ransom
- 299,747
- 42
- 398
- 622
-
What if the color is RGBA (1, 1, 1, 1)? – Ricardo Sanchez Aug 05 '11 at 19:48
-
@Ricardo, the inverse of RGBA(1,1,1,1) is RGBA(0,0,0,1). Is there something confusing about the answer that made this not obvious? – Mark Ransom Aug 05 '11 at 19:52
-
what about RGBA(1,0,0,0.5) would become RGBA(-0.5,0,0,0.5)? shouldnt an abs() take place here? also an over/underflow (<0 >1) limits? – Aquarius Power Aug 13 '16 at 19:01
-
3@AquariusPower notice I said "premultiplied" alpha, which means that none of the R,G,B can be greater than A. If the initial values are in bounds the inverted ones will be as well, no need to check for over/underflow. – Mark Ransom Aug 13 '16 at 19:40
-
If your intent is to make contrasting colors (e.g. bright letters over a dark background) it will result in poor contrast for colors near 50% gray. – Paulo Carvalho Feb 14 '19 at 14:45
-
@PauloCarvalho exactly, which is why I have an answer on [How to decide font color in white or black depending on background color?](https://stackoverflow.com/a/3943023/5987). – Mark Ransom Feb 14 '19 at 17:02
10
If you are using RGB values to 255, you could do something like this:
newR = 255 - r;
newG = 255 - g;
newB = 255 - b;
To understand this concept, imagine each value as a number line going from 0 to 255. If you graph a number on that number line then the number is that distance away from the beginning of the number line. In order to negate it, the number must travel to the other end of the number line. This algorithm basically flips the number line without moving the beginning or the end. Our number line is from 0 to 255, so, if the number was 10 away from the beginning (10), now it will be 10 away from the end (245), thus negating the color.

NonameSL
- 1,405
- 14
- 27

Ptolemy2002
- 169
- 2
- 15
-
2
-
@CarlH What is the problem? 255-127 = 128 and it is a valid color value in the range 0...255 (256 palette). – rbaleksandar Dec 17 '21 at 15:20
-
@rbaleksandar The closer you get to 127,127,127, the inverse gets closer to the original value. The inverse of 127,127,127 would be 128,128,128, which is almost the same colour. – Carl H Dec 19 '21 at 22:13
-
@CarlH I still don't see the issue here. What does "almost the same colour" have to do with the process of inverting? It's purpose is - as far as I know - to invert and not to add more colours to an image. :P – rbaleksandar Dec 20 '21 at 07:55