美文网首页
Android实现灰度模式

Android实现灰度模式

作者: 一城山水一成伤 | 来源:发表于2022-12-04 09:49 被阅读0次

    App快速实现“哀悼主题”方案
    全局设置灰白模式:

        @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);
        }
    

    创建一个置灰的管理类

    
    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);
            //view.setLayerType(View.LAYER_TYPE_SOFTWARE, mGrayPaint); 不能用硬件加速的方法
        }
    }
    

    特殊控件需要置灰的话直接调用setLayerGrayType()方法将view传进去,比如demo中让某个Activity置灰,那就在Activity里面调用

    GrayManager.getInstance().setLayerGrayType(getWindow().getDecorView());
    

    相关文章

      网友评论

          本文标题:Android实现灰度模式

          本文链接:https://www.haomeiwen.com/subject/tgxvfdtx.html