反转可绘制对象的颜色

27

在一个Drawable中“反转”颜色是否可能?就像在负片中那样,你知道的吗?

我知道可以将Drawable更改为黑白,但是反转颜色怎么办?

3个回答

67

经过一些研究,我发现解决方案比我想象的要简单得多。

就是这样:

  /**
   * 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));

3
谢谢。同时,这适用于任何来源的图像视图(drawable、bitmap等)。只需执行相同的操作:imageView.setColorFilter(new ColorMatrixColorFilter(NEGATIVE)) - Leo DroidCoder

2
最好的方法是将您的可绘制对象转换为位图:
Bitmap fromDrawable = BitmapFactory.decodeResource(context.getResources(),R.drawable.drawable_resource);

然后按照以下方式反转它:

https://dev59.com/41PTa4cB1Zd3GeqPhDF1#4625618

如果需要,您可以将其转换回可绘制的格式:

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

1
根据你的回答,我创建了一个短的 Kotlin 扩展程序用于 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)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接