置灰前:
image.png
置灰后:
image.png
Android页面置灰
方案1.Android页面绘制流程一般分为measure、layout、draw,页面置灰在draw方法中实现。draw方法参数有canvas、paint,canvas是界面的画布,paint是绘制界面的画笔。可以通过更改paint的属性更改界面背景颜色,通过设置颜色过滤器更改画笔的色调、饱和度和亮度。置灰效果饱和度为0,画笔的设置代码:
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setStaturation(0);
paint.setColorFilter(new ColorMatrixColorFilter(cm));
方案2.考虑性能使用HardwareLayer(GPU内部的Buffer)对绘制的图形进行缓存。设置方法setLayerType()强制View创建自己对应的层,并将自己绘制到层上。
方案3.给Activity的顶层View设置置灰,实现全局置灰效果。获取界面的根View:
//java
View view = activity. getWindow(). getDecorView();
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setStaturation(0);
paint.setColorFilter(new ColorMatrixColorFilter(cm));
view. setLayerType(View.LAYER_TYPE_HARDWARE, paint);
//kotlin
val view: View = window.decorView
val paint = Paint()
val cm = ColorMatrix()
cm.setSaturation(0f)
paint.colorFilter = ColorMatrixColorFilter(cm)
view.setLayerType(View.LAYER_TYPE_HARDWARE, paint)
网友评论