title: How to mask/crop a rectangle in ImageView
body: <p>I have created a custom <code>ImageView</code> to create a transparent rectangle within the image so to make the ImageView behind it visible. However, I can't get it right. I've looked at many other answers and this is what I have came up with:</p>
  
  <pre><code>public class MaskImageView extends ImageView {
      private Paint maskPaint;
  
      public MaskImageView(Context context) {
          super(context);
          init();
      }
  
      public MaskImageView(Context context, AttributeSet attrs) {
          super(context, attrs);
          init();
      }
  
      public MaskImageView(Context context, AttributeSet attrs, int defStyleAttr) {
          super(context, attrs, defStyleAttr);
          init();
      }
  
      @TargetApi(Build.VERSION_CODES.LOLLIPOP)
      public MaskImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
          super(context, attrs, defStyleAttr, defStyleRes);
          init();
      }
  
      public void init() {
          maskPaint = new Paint();
          maskPaint.setColor(Color.TRANSPARENT);
          maskPaint.setAntiAlias(true);
          maskPaint.setStyle(Paint.Style.FILL);
          maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
      }
  
      @Override
      protected void onDraw(Canvas canvas) {
          super.onDraw(canvas);
          canvas.drawRect(100, 400, 900, 900, maskPaint);
      }
  
      public void setMaskWidth(int width) {
          maskWidth = width;
      }
  }
  </code></pre>
  
  <p>And this is the XML layout:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;RelativeLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"&gt;
  
      &lt;ImageView
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/holo_red_dark"
          android:scaleType="centerCrop"
          android:src="@drawable/blackwhite" /&gt;
  
  
      &lt;io.example.test.MaskImageView
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/holo_red_dark"
          android:scaleType="centerCrop"
          android:src="@drawable/color" /&gt;
  &lt;/RelativeLayout&gt;
  </code></pre>
  
  <p>I get the photo on the left but I want it to look like the photo on the right. Note that the normal <code>ImageView</code> drawable is the grayscale version of the photo of <code>MaskImageView</code>.</p>
  
  <p><img src="https://i.stack.imgur.com/zM048.jpg" alt="enter image description here"></p>