如何在android中使用mask

时间:2011-11-13 23:43:20

标签: android

我正在尝试使用面具。 我想使用一个图像来显示底层图像的一部分。 例如。我有一个箭头暴露了一个底层(红色)方块的一部分。 我的问题是,虽然蒙版工作,但任何未曝光的东西都会呈现为黑色矩形,而我想要一个透明的背景。我的箭头图像有一个透明的画布。

我的代码是:

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/

,您可以了解我的意思

1 个答案:

答案 0 :(得分:0)

您需要在Bitmap中再添加一个MaskAttempt

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();
}