Invert colors of drawable

Carlos Pereira picture Carlos Pereira · Jul 24, 2013 · Viewed 16.2k times · Source

Is it possible to "invert" colors in a Drawable? Kind of what you have in a negative, you know?

I know it's possible to change a Drawable to black and white, but what about inverting colors?

Answer

Carlos Pereira picture Carlos Pereira · Jul 26, 2013

After some research I found out that solution is much simpler than I thought.

Here it is:

  /**
   * Color matrix that flips the components (<code>-1.0f * c + 255 = 255 - c</code>)
   * and keeps the alpha intact.
   */
  private static final float[] NEGATIVE = { 
    -1.0f,     0,     0,    0, 255, // red
        0, -1.0f,     0,    0, 255, // green
        0,     0, -1.0f,    0, 255, // blue
        0,     0,     0, 1.0f,   0  // alpha  
  };

  drawable.setColorFilter(new ColorMatrixColorFilter(NEGATIVE));