方案一:可以在BaseActivity的onCreate方法中,使用ColorMatrix设置灰度
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);//灰度效果
paint.setColorFilter(new ColorMatrixColorFilter(cm));
getWindow().getDecorView().setLayerType(View.LAYER_TYPE_HARDWARE,paint);
}
方案二:使用自定义layout,在dispatchdraw方法的时候,添加一层黑白色的bitmap,让界面开起来成为黑白模式。但是缺点明显,应用比较卡顿。
1、首先需要先定义一个GrayFrameLayout布局
public class GrayFrameLayout extends FrameLayout {
private Paint mPaint = new Paint();
public GrayFrameLayout(@NonNull Context context) {
super(context);
}
public GrayFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
mPaint.setColorFilter(new ColorMatrixColorFilter(cm));
}
@Override
protected void onDraw(Canvas canvas) {
canvas.saveLayer(null, mPaint, Canvas.ALL_SAVE_FLAG);
super.onDraw(canvas);
}
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.saveLayer(null, mPaint, Canvas.ALL_SAVE_FLAG);
super.dispatchDraw(canvas);
}
}
2、在BaseActivity的onCreateView方法中做如下处理
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
//方案二
if("FrameLayout".equals(name)){
int attributeCount = attrs.getAttributeCount();
for (int i = 0; i < attributeCount; i++) {
String attributeName = attrs.getAttributeName(i);
String attributeValue = attrs.getAttributeValue(i);
if(attributeName.equals("id")){
int id = Integer.parseInt(attributeValue.substring(1));
String resourceName = getResources().getResourceName(id);
if("android:id/content".equals(resourceName)){
GrayFrameLayout frameLayout = new GrayFrameLayout(this,attrs);
return frameLayout;
}
}
}
}
return super.onCreateView(parent, name, context, attrs);
}
方案三
有些特殊控件需要置灰,比如webview、H5页面、视频等
1、创建一个置灰的管理类
public class GrayManager {
private static GrayManager mInstance;
private Paint mGrayPaint;
private ColorMatrix mGrayMatrix;
public static GrayManager getInstance() {
if (mInstance == null) {
synchronized (GrayManager.class) {
if (mInstance == null) {
mInstance = new GrayManager();
}
}
}
return mInstance;
}
//初始化
public void init() {
mGrayMatrix = new ColorMatrix();
mGrayPaint = new Paint();
mGrayMatrix.setSaturation(0);
mGrayPaint.setColorFilter(new ColorMatrixColorFilter(mGrayMatrix));
}
//硬件加速置灰方法
public void setLayerGrayType(View view) {
if (mGrayMatrix == null || mGrayPaint == null) {
init();
}
view.setLayerType(View.LAYER_TYPE_HARDWARE, mGrayPaint);
}
}
2、特殊控件需要置灰的话直接调用setLayerGrayType()方法将view传进去,比如demo中让某个Activity置灰,那就在Activity里面调用:
GrayManager.getInstance().setLayerGrayType(getWindow().getDecorView());
以上三种方案都可以实现灰白模式,也是经过demo测试验证的,不过可能由于测试范围比较狭隘,所以可能还有其它情况,那就后面遇到再补充吧,今天的内容就到这里啦。