android - 如何在android中使用面具

标签 android

我正在尝试使用面具。 我想使用一个图像来暴露底层图像的一部分。 例如。我有一个箭头,它暴露了底层(红色)方 block 的一部分。 我的问题是,尽管蒙版有效,但任何未暴露的内容都呈现为黑色矩形,而我想要透明背景。我的箭头图像有透明 Canvas 。

我的代码是:

private class MaskAttempt extends View {

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

        private Bitmap mItemToBeMasked;
        private Bitmap mMask;

        public MaskAttempt(Context context) {
            super(context);
            this.setBackgroundColor(Color.WHITE);
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

                final Resources res = context.getResources();
            mItemToBeMasked = BitmapFactory.decodeResource(res, R.drawable.red_rectangle);
            mMask = BitmapFactory.decodeResource(res, R.drawable.icon_mask);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.save();

            canvas.translate((getWidth() - mItemToBeMasked.getWidth()) >> 1, (getHeight() -     mItemToBeMasked.getHeight()) >> 1);

            canvas.drawBitmap(mItemToBeMasked, 0, 0, null);
            canvas.drawBitmap(mMask, 0, 0, mPaint);

            canvas.restore();
        }

您可以通过查看http://www.steveharris100.pwp.blueyonder.co.uk/ 来了解我的意思。

最佳答案

您需要在MaskAttempt 中添加一个Bitmap

public MaskAttempt(Context context) {
    super(context);
    this.setBackgroundColor(Color.WHITE);
    mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

    final Resources res = context.getResources();
    mItemToBeMasked = BitmapFactory.decodeResource(res, R.drawable.red_rectangle);
    mMask = BitmapFactory.decodeResource(res, R.drawable.icon_mask);
    duplicate = BitmapFactory.decodeResource(res, R.drawable.icon_mask).copy(Config.ARGB_8888, true);

    c = new Canvas(duplicate);

    x = new Paint(Paint.ANTI_ALIAS_FLAG);
    x.setColor(Color.BLACK);
    x.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();

    canvas.translate((getWidth() - mItemToBeMasked.getWidth()) >> 1, (getHeight() -     mItemToBeMasked.getHeight()) >> 1);

    c.drawBitmap(mItemToBeMasked, 0, 0, null);
    c.drawBitmap(mMask, 0, 0, mPaint);
    canvas.drawBitmap(duplicate, 0, 0, null);

    canvas.restore();
}

关于android - 如何在android中使用面具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8115732/

相关文章:

java - 暂停所有线程花费了 : ms warning using Threads - Android

android - 存储访问框架不更新 MediaScanner (MTP)

android - 对异步图像加载感到困惑

android - Kotlin 可见性 view.gone 在单击时崩溃

android - 在 RecyclerView Scrolling 上只创建一个按钮

android - 如何在android中显示数据库中的所有行

Android View - 在 Activity 中自动保存和恢复的内容

java - 如何在 AlertDialog 之后显示 ProgressDialog

所有 Android 项目中的 Android 启动错误

android - 如何检测 Android 设备上的硬/软后退按钮?