Android App 黑白化技术实践与方案分析
前言
近期打开各大 App 会发现它们都做了黑白化处理,例如支付宝等应用设置了全局灰色调,表达对逝者的哀悼。作为开发者,我们来探索一下它从技术角度是如何实现的。
一、App 黑白化实现原理
1.1、修改 Canvas 的 Paint 实现黑白化
正常情况下,App 页面上的 View 都是通过 Canvas(画布)+ Paint(画笔)画出来的。Canvas 对应画布,Paint 对应画笔,两者结合,就能画出 View。
在 Canvas 上绘制 View 的时候,如果换一支色彩饱和度为 0 的 Paint(画笔),理论上就能画出黑白化的 View。
可以通过 ColorMatrix 将饱和度设置为 0:
// 新建一支画笔
val paint = Paint()
// 通过 ColorMatrix 将饱和度设置为 0
val cm = ColorMatrix()
cm.setSaturation(0f)
// 将画笔的色彩饱和度设置为 0
paint.colorFilter = ColorMatrixColorFilter(cm)
上述代码新建了一支色彩饱和度为 0 的 Paint,接下来使用它去进行 View 的绘制,就能达到黑白化的效果。
测试示例:自定义黑白化 TextView 和 Button。
// 1、自定义黑白化 TextView
class GrayTextView(context: Context, attrs: AttributeSet) : TextView(context, attrs) {
// 色彩饱和度为 0 的 Paint
private val paint by lazy {
val p = Paint()
val cm = ColorMatrix()
cm.setSaturation(0f)
p.colorFilter = ColorMatrixColorFilter(cm)
p
}
override fun draw(canvas: Canvas?) {
canvas?.saveLayer(null, paint, Canvas.ALL_SAVE_FLAG)
super.draw(canvas)
canvas?.restore()
}
}
// 2、自定义黑白化 Button
class GrayButton(context: Context, attrs: AttributeSet) : Button(context, attrs) {
// 色彩饱和度为 0 的 Paint
private paint lazy {
p = Paint()
cm = ColorMatrix()
cm.setSaturation()
p.colorFilter = ColorMatrixColorFilter(cm)
p
}
{
canvas?.saveLayer(, paint, Canvas.ALL_SAVE_FLAG)
.draw(canvas)
canvas?.restore()
}
}


