Invert colors of drawable Android

一个人想着一个人 提交于 2019-11-28 05:04:10
Carlos Pereira

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));
VicVu

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://stackoverflow.com/a/4625618/1154026

And then back to a drawable if you need to:

Drawable invertedDrawable = new BitmapDrawable(getResources(),fromDrawable);

According your answer I 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)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!