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

前端 未结 5 601
误落风尘
误落风尘 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:10

    It's easy to do that by defining a custom view group as follows:

    public class MyViewContainer extends XXXLayout {
        //XXLayout could be LinearLayout, RelativeLayout or others
        private Paint m_paint;
    
        //define constructors here and call _Init() at the end of constructor function
    
        private void
        _Init()
        {
            ColorMatrix cm = new ColorMatrix();
            cm.setSaturation(0);
            m_paint = new Paint();
            m_paint.setColorFilter(new ColorMatrixColorFilter(cm));
        }
    
        @Override protected void 
        dispatchDraw(Canvas canvas)
        {
            canvas.saveLayer(null, m_paint, Canvas.ALL_SAVE_FLAG);
            super.dispatchDraw(canvas);
            canvas.restore();
        }
    }
    

    All children views of MyViewContainer will be shown in grey. :-)

提交回复
热议问题