置灰前:
置灰后:
Android頁面置灰
方案1.Android頁面繪制流程一般分為measure艰山、layout锌历、draw隘擎,頁面置灰在draw方法中實現(xiàn)。draw方法參數(shù)有canvas狱窘、paint,canvas是界面的畫布财搁,paint是繪制界面的畫筆蘸炸。可以通過更改paint的屬性更改界面背景顏色尖奔,通過設置顏色過濾器更改畫筆的色調(diào)搭儒、飽和度和亮度。置灰效果飽和度為0提茁,畫筆的設置代碼:
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setStaturation(0);
paint.setColorFilter(new ColorMatrixColorFilter(cm));
方案2.考慮性能使用HardwareLayer(GPU內(nèi)部的Buffer)對繪制的圖形進行緩存淹禾。設置方法setLayerType()強制View創(chuàng)建自己對應的層,并將自己繪制到層上甘凭。
方案3.給Activity的頂層View設置置灰稀拐,實現(xiàn)全局置灰效果。獲取界面的根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)