Search code examples
androidandroid-layoutimageviewporter-duffcolorfilter

ImageView - ColorFilter


I have an ImageView and use a ColorFilter (PorterDuff.Mode.MULTIPLY).

Is it possible to use this colorFilter but not on the whole image? It must be like a 'margin' / 'padding'.

Example: The image width and height = 100dp. But the colorFilter must be 50dp (width and height) on the center of the ImageView.

The picture below is what I need (red = colorFilter)

enter image description here


Solution

  • You can subclass ImageView and override its onDraw() method. I am posting a minimalictic solution, modify to your needs!

    public class OverlayImageView extends ImageView {
        Paint paint;
        float padding = 30;
    
        public OverlayImageView(Context context) {
            super(context);
            init();
        }
    
        public OverlayImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public OverlayImageView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init();
        }
    
        private void init() {
            paint = new Paint();
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
            paint.setColor(Color.RED);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
    
            canvas.drawRect(padding, padding, canvas.getWidth()-padding, canvas.getHeight()-padding, paint);
        }
    }