[英]Invert colors of drawable
Is it possible to "invert" colors in a Drawable
?是否可以在Drawable
“反转”颜色? Kind of what you have in a negative, you know?你有什么消极的东西,你知道吗?
I know it's possible to change a Drawable
to black and white, but what about inverting colors?我知道可以将Drawable
更改为黑白,但是反转颜色呢?
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));
Best way to do this would be to convert your drawable into a bitmap:最好的方法是将 drawable 转换为位图:
Bitmap fromDrawable = BitmapFactory.decodeResource(context.getResources(),R.drawable.drawable_resource);
And then invert it as per:然后按照以下方式将其反转:
https://stackoverflow.com/a/4625618/1154026 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've created short Kotlin extension for Drawable根据您的回答,我为 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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.