是否可以在 a 中“反转”颜色Drawable
?你有什么负面的,你知道吗?
我知道可以将 a 更改Drawable
为黑白,但是反转颜色呢?
经过一番研究,我发现解决方案比我想象的要简单得多。
这里是:
/**
* 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));
最好的方法是将您的drawable转换为位图:
Bitmap fromDrawable = BitmapFactory.decodeResource(context.getResources(),R.drawable.drawable_resource);
然后按以下方式反转它:
https://stackoverflow.com/a/4625618/1154026
如果您需要,然后返回到可绘制对象:
Drawable invertedDrawable = new BitmapDrawable(getResources(),fromDrawable);
根据您的回答,我为 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)
}