androidandroid-custom-viewcustom-draw

Draw only portion of a custom view


I have a custom view which is a RelativeLayout which contains a ListView (both are set to match parent - width and height). On top of the list I have a View as seen in the picture below: My Custom View

I want that the only part that will be drawn is the rect of my View (marked with gray), while all the other portion of the view will be transparent.

is there a way I can do this? I already tried to extend RelativeLayout and override its onDraw() method, but I didn't manage to draw only the specific region (marked in gray).


Solution

  • Eventually, I did it by extending RelativeLayout and override its draw() method.

    @Override
    protected void draw(Canvas canvas) {
        canvas.clipRect(magnifiedRegion.getLeft(), magnifiedRegion.getTop(), magnifiedRegion.getRight(), magnifiedRegion.getBottom());
        super.draw(canvas);
    }
    

    where magnifiedRegion is my View as it mentioned in the question above.

    Note: you must set this.setWillNotDraw(false); in the constructor or else, draw() method won't be called by the framework (since our root view is a ViewGroup - it's an optimization Android framework does by default).