2

我正在尝试使用蒙版来隐藏图片的一部分,具体取决于用户触摸屏幕的位置。为此,我遵循了Cyril Mottier 提供的代码示例。到目前为止,我所做的实际上是有效的:单击 ImageView 的一部分时,我上面得到的所有内容都被隐藏了。问题是它被黑色隐藏,阻止了我的 ImageView 后面的内容显示。

有人可以给我提示或告诉我我做错了什么吗?

这是我当时得到的屏幕

这是主要活动:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

    final MaskedImageView iv = (MaskedImageView) findViewById(R.id.picture_on);
    iv.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Log.d(MainActivity.class.getSimpleName(), "on touch called");

            Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay();
            Point point = new Point();
            display.getSize(point);

            Rect bounds = iv.getDrawable().getBounds();
            bounds.top = point.y
                    - (int) event.getY()
                    ;
            iv.setMask(bounds);
            iv.invalidate();
            return false;
        }
    });
}

这里是自定义 ImageView :

public class MaskedImageView extends ImageView {

    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private Bitmap mMask;

    public MaskedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        // Prepares the paint that will be used to draw our icon mask. Using
        // PorterDuff.Mode.DST_IN means the image that will be drawn will
        // mask the already drawn image.
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
    }

    public MaskedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // Prepares the paint that will be used to draw our icon mask. Using
        // PorterDuff.Mode.DST_IN means the image that will be drawn will
        // mask the already drawn image.
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
    }

    public MaskedImageView(Context context) {
        super(context);

        // Prepares the paint that will be used to draw our icon mask. Using
        // PorterDuff.Mode.DST_IN means the image that will be drawn will
        // mask the already drawn image.
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
    }

    public void setMask(Rect rect) {
        mMask = Bitmap.createBitmap(Math.abs(rect.right - rect.left),
                Math.abs(rect.bottom - rect.top), Bitmap.Config.ALPHA_8);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        BitmapDrawable bd = (BitmapDrawable) getDrawable();
        canvas.drawBitmap(bd.getBitmap(), 0, 0, null);

        if (mMask != null) {
            canvas.drawBitmap(mMask, 0, 0, mPaint);
        }
        canvas.restore();
    }


}

谢谢您的回答

4

0 回答 0