简体   繁体   English

无法将位图修改为在Android中透明

[英]Unable to modify Bitmap to be transparent in Android

I am trying to draw a transparent circle on a Bitmap in android. 我试图在android中的位图上绘制一个透明的圆圈。 I have three primary variables: 我有三个主要变量:

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

If I do the following, I get my expected results: 如果执行以下操作,则会得到预期的结果:

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

在此处输入图片说明

However, if I draw something else on the canvas first, then try to clear it out with transparency, the old data remains. 但是,如果我先在画布上绘制其他内容,然后尝试以透明方式清除它,则旧数据仍然保留。 For example: 例如:

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

在此处输入图片说明

I only see a giant red square. 我只看到一个巨大的红场。 The bottom two lines are supposed to "erase" the filled red to make it transparent again. 底部的两行应该“擦除”填充的红色以使其再次透明。 Ultimately the mask is drawn on another canvas like this: 最终,蒙版被绘制在另一个画布上,如下所示:

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

    super.onDraw(c);
}

As it turns out it does have to do with the Paint object and setting the Xfermode... 事实证明,这确实与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);

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM