How to apply a color filter to a view with all children

前端 未结 5 602
误落风尘
误落风尘 2020-12-24 02:45

How do I grey out a view uniformly which contains many different items - ImageViews, TextViews, background image. Do I have to grey out each thing individually? Or is there

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-24 03:18

    Sam Lu's answer is a good start, but I had performance problems and decided to switch to hardware layers. With hardware layers, you can do it like this:

    private final Paint grayscalePaint = new Paint();
    
    ColorMatrix cm = new ColorMatrix();
    cm.setSaturation(0);        
    grayscalePaint.setColorFilter(new ColorMatrixColorFilter(cm));
    
    public void setGrayedOut(boolean grayedOut) {       
        if (grayedOut) {
            setLayerType(View.LAYER_TYPE_HARDWARE, grayscalePaint);
        } else {
            setLayerType(View.LAYER_TYPE_NONE, null);       
        }       
    }
    

    Be careful not to do the layers in dispatchDraw() itself as that will crash the app.

提交回复
热议问题