我已經創建了一個自定義ImageView
在圖像中創建一個透明的矩形,以使其後面的ImageView可見。但是,我無法做到。我已經看了很多其他的答案,這就是我想出了:如何在ImageView中遮罩/裁剪一個矩形
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;
}
}
這是XML佈局:
<?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>
我上留下的照片,但我想它看起來像右邊的照片。請注意,正常的ImageView
drawable是MaskImageView
照片的灰度版本。
你需要什麼?用戶裁剪圖像的自定義視圖? –