27

是否可以在 a 中“反转”颜色Drawable?你有什么负面的,你知道吗?

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

4

3 回答 3

66

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

这里是:

  /**
   * 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));
于 2013-07-26T01:21:26.900 回答
2

最好的方法是将您的drawable转换为位图:

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

然后按以下方式反转它:

https://stackoverflow.com/a/4625618/1154026

如果您需要,然后返回到可绘制对象:

Drawable invertedDrawable = new BitmapDrawable(getResources(),fromDrawable);
于 2013-07-24T18:21:41.750 回答
1

根据您的回答,我为 Drawable 创建了简短的 Kotlin 扩展

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)
}
于 2019-06-18T11:39:19.020 回答