Invert colors of drawable
Asked Answered
S

4

27

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?

Sax answered 24/7, 2013 at 18:16 Comment(0)
S
67

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));
Sax answered 26/7, 2013 at 1:21 Comment(1)
Thanks. Also, it works for an image view with any source (drawable, bitmap, etc.). Just do the same imageView.setColorFilter(new ColorMatrixColorFilter(NEGATIVE))Jewess
H
2

Best way to do this would be to convert your drawable into a bitmap:

Bitmap fromDrawable = BitmapFactory.decodeResource(context.getResources(),R.drawable.drawable_resource);

And then invert it as per:

https://mcmap.net/q/505387/-invert-bitmap-colors

And then back to a drawable if you need to:

Drawable invertedDrawable = new BitmapDrawable(getResources(),fromDrawable);
Heliolatry answered 24/7, 2013 at 18:21 Comment(0)
S
1

According your answer, I've created short Kotlin extension for Drawable

private val negative = floatArrayOf(
    -1.0f,     .0f,     .0f,    .0f,  255.0f, 
      .0f,   -1.0f,     .0f,    .0f,  255.0f, 
      .0f,     .0f,   -1.0f,    .0f,  255.0f, 
      .0f,     .0f,     .0f,   1.0f,     .0f 
)

fun Drawable.toNegative() {
    this.colorFilter = ColorMatrixColorFilter(negative)
}
Soane answered 18/6, 2019 at 11:39 Comment(0)
R
0

kotlin extension function for ImageView:

fun ImageView.invertColors() {
    val colorFilter = PorterDuffColorFilter(0xffffffff.toInt(), PorterDuff.Mode.SRC_IN)
    setColorFilter(colorFilter)
}

and also for Drawable

fun Drawable.invertColors() {
    val colorFilter = PorterDuffColorFilter(0xffffffff.toInt(), PorterDuff.Mode.SRC_IN)
    setColorFilter(colorFilter)
}
Richela answered 23/12, 2023 at 6:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.