[英]Invert colors of drawable
是否可以在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));
最好的方法是将 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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.