首页 > 解决方案 > 无法在 Android 中将位图修改为透明

问题描述

我正在尝试在 android 的 Bitmap 上绘制一个透明的圆圈。我有三个主要变量:

        mask = Bitmap.createBitmap(this.getWidth(),this.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas can = new Canvas(mask);
        Paint clear = new Paint();

如果我执行以下操作,我会得到预期的结果:

clear.setColor(Color.TRANSPARENT);
can.drawRect(new Rect(0,0,this.getWidth(),this.getHeight()),clear);

在此处输入图像描述

但是,如果我先在画布上绘制其他东西,然后尝试用透明度清除它,旧数据仍然存在。例如:

clear.setColor(Color.argb(255,255,0,0));
can.drawRect(new Rect(0,0,this.getWidth(),this.getHeight()),clear);
clear.setColor(Color.TRANSPARENT);
can.drawRect(new Rect(0,0,this.getWidth(),this.getHeight()),clear);

在此处输入图像描述

我只看到一个巨大的红色方块。底部的两行应该“擦除”填充的红色以使其再次透明。最终,面具被绘制在另一个画布上,如下所示:

@Override
public void onDraw(Canvas c)
{
    c.drawBitmap(mask,0,0,null);

    super.onDraw(c);
}

标签: javaandroidbitmaptransparency

解决方案


事实证明,它确实与Paint对象和设置 Xfermode ...

    mask = Bitmap.createBitmap(this.getWidth(),this.getHeight(), 
    Bitmap.Config.ARGB_8888);
    Canvas can = new Canvas(mask);

    Paint clear = new Paint();
    clear.setColor(Color.argb(255,255,0,0));
    can.drawRect(new Rect(0,0,this.getWidth(),this.getHeight()),clear);

    PorterDuffXfermode xfer = new PorterDuffXfermode(PorterDuff.Mode.CLEAR);
    clear.setXfermode(xfer);
    clear.setColor(Color.TRANSPARENT);
    can.drawCircle(this.getWidth()/2, this.getHeight()/2, this.getHeight()/2, clear);

在此处输入图像描述


推荐阅读