Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 a way to apply the same color filter to all?

like image 248
User Avatar asked Jun 14 '12 15:06

User


2 Answers

Unless somebody else has a better answer, my current method is greying out each item separatedly.

PorterDuffColorFilter greyFilter = new PorterDuffColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY); myLayout.getBackground().setColorFilter(greyFilter); myImageView.setColorFilter(greyFilter); myTextView.setTextColor(0xff777777); 

For more or nested children probably a loop with instanceof would be suitable but I don't need it.

Edit: This filter isn't actually grey, a better filter is here: Drawable => grayscale Which can be used in the same way.

like image 97
User Avatar answered Sep 26 '22 03:09

User


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. :-)

like image 44
Sam Lu Avatar answered Sep 22 '22 03:09

Sam Lu