安卓APP全局黑白化

时间:2023-02-18 18:58:45

在清明节时各APP都会进行黑白化处理,要怎么实现呢?

一、原理

Android提供的ColorMatrix(颜色矩阵),将其饱和度设置为0,这样使用Paint绘制出来的都是没有饱和度的灰白样式:

Paint paint = new Paint();
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0);
paint.setColorFilter(new ColorMatrixColorFilter(colorMatrix));

全局黑白化,我们需要将每个Activity的根(DecorView)布局饱和度设置为0。可以在Activity的onCreate中执行

getWindow().getDecorView().setLayerType(View.LAYER_TYPE_HARDWARE,paint);

二、实现方案

在Application的onCreate方法里面调用registerActivityLifecycleCallbacks注册监听,监听里面的onActivityCreated(此方法里可以获取到当前的Activity)方法里执行:

activity.getDecorView().setLayerType(View.LAYER_TYPE_HARDWARE,paint);

三、注意事项

3.1 启动图windowBackground无法变色

在我们可以设置渲染的时候windowBackground已经展示完毕了。

解决方案:只能在当前的包里修改,或者不去理会。

3.2 SurfaceView无法变色

因为我们使用了setLayerType进行重绘,而SurfaceView是有独立的Window,脱离布局内的Window,运行在其他线程,不影响主线程的绘制,所以当前方案无法使SurfaceView变色。

解决方案:

1、使用TextureView。

2、看下这个SurfaceView是否可以设置滤镜,正常都是一些三方或者自制的播放器。