views:

1197

answers:

3

I know that this won't directly invert a colour, it will just 'oppose' it. I was wondering if anyone knew a simple way (a few lines of code) to invert a colour from any given colour?

At the moment I have this (which isn't exactly the definition of an invert):

const int RGBMAX = 255;

Color InvertMeAColour(Color ColourToInvert)
{
    return Color.FromArgb(RGBMAX - ColourToInvert.R, 
      RGBMAX - ColourToInvert.G, RGBMAX - ColourToInvert.B);
}
+3  A: 

Try this:

uint InvertColor(uint rgbaColor)
{
    return 0xFFFFFF00u ^ rgbaColor; // Assumes alpha is in the rightmost byte, change as needed
}
korona
it is done the same way in C#. The syntax is exactly the same. 0xFFFFFFFF ^ color
Nick Berardi
Almost identical. :) I just made the minor changes to turn it into C#.
Noldorin
This is the same as the code in the question
Eyal
@Eyal, no its different. Here XOR operation is used instead of -.
modosansreves
+2  A: 

Invert the bits of each component separately:

Color InvertMeAColour(Color ColourToInvert)
{
   return Color.FromArgb((byte)~ColourToInvert.R, (byte)~ColourToInvert.G, (byte)~ColourToInvert.B);
}

EDIT: The ~ operator does not work with bytes automatically, cast is needed.

kek444
This throws an exception (ArgumentException "Value of '-129' is not valid for 'red'")
ThePower
Yep, missed that one, corrected answer.
kek444
Now it's been edited that's better, although it still does the same as my function with regards to being a negative, not an invert. thanks for the answer anyway :-)
ThePower
+13  A: 

It depends on what do you mean by "inverting" a color

Your code provides a "negative" color.

Are you looking for transform red in cyan, green in purple, blue in yellow (and so on) ? If so, you need to convert your RGB color in HSV mode (you will find here to make the transformation).

Then you just need to invert the Hue value (change Hue by 360-Hue) and convert back to RGB mode.

ThibThib
yup, finally a meaningful answer. +1
jalf