I have created a custom ImageView
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:
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;
}
}
And this is the XML layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<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" />
<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" />
</RelativeLayout>
I get the photo on the left but I want it to look like the photo on the right. Note that the normal ImageView
drawable is the grayscale version of the photo of MaskImageView
.