安卓实现图片反色,改色-ColorMatrixColorFilt
2020-09-10 本文已影响0人
蓝不蓝编程
效果图
原图过滤蓝光
反色
主要代码
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
filterBlueLightBtn.setOnClickListener { filterBlueLight() }
reverseColorBtn.setOnClickListener { reverseColor() }
resumeBtn.setOnClickListener { resumeColor() }
}
/**
* 反色
*/
private fun reverseColor() {
val paint = Paint()
val cm = ColorMatrix(floatArrayOf(
-1f, 0f, 0f, 0f, 255f,
0f, -1f, 0f, 0f, 255f,
0f, 0f, -1f, 0f, 255f,
0f, 0f, 0f, 1f, 0f))
paint.colorFilter = ColorMatrixColorFilter(cm)
window.decorView.setLayerType(View.LAYER_TYPE_HARDWARE, paint)
}
/**
* 过滤蓝光
*/
private fun filterBlueLight() {
val paint = Paint()
// 把蓝色减弱为原来的0.7
val cm = ColorMatrix(floatArrayOf(
1f, 0f, 0f, 0f, 0f,
0f, 1f, 0f, 0f, 0f,
0f, 0f, 0.7f, 0f, 0f,
0f, 0f, 0f, 1f, 0f))
paint.colorFilter = ColorMatrixColorFilter(cm)
window.decorView.setLayerType(View.LAYER_TYPE_HARDWARE, paint)
}
/**
* 恢复
*/
private fun resumeColor() {
window.decorView.setLayerType(View.LAYER_TYPE_HARDWARE, Paint())
}
}
完整源代码
https://gitee.com/cxyzy1/ColorMatrixColorFilterDemo
附录
这种方式是基于view做的修改,也可直接针对ImageView设置颜色过滤器,详见:https://www.jianshu.com/p/f1f93a37738b