在一个Drawable
中“反转”颜色是否可能?就像在负片中那样,你知道的吗?
我知道可以将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));
Bitmap fromDrawable = BitmapFactory.decodeResource(context.getResources(),R.drawable.drawable_resource);
然后按照以下方式反转它:
https://dev59.com/41PTa4cB1Zd3GeqPhDF1#4625618
如果需要,您可以将其转换回可绘制的格式:
Drawable invertedDrawable = new BitmapDrawable(getResources(),fromDrawable);
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)
}
imageView.setColorFilter(new ColorMatrixColorFilter(NEGATIVE))
- Leo DroidCoder