How to make bitmap transparent?

徘徊边缘 提交于 2019-12-01 08:45:52
// Convert transparentColor to be transparent in a Bitmap.
public static Bitmap makeTransparent(Bitmap bit, Color transparentColor) {
    int width =  bit.getWidth();
    int height = bit.getHeight();
    Bitmap myBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    int [] allpixels = new int [ myBitmap.getHeight()*myBitmap.getWidth()];
    bit.getPixels(allpixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(),myBitmap.getHeight());
    myBitmap.setPixels(allpixels, 0, width, 0, 0, width, height);

    for(int i =0; i<myBitmap.getHeight()*myBitmap.getWidth();i++){
     if( allpixels[i] == transparentColor)

                 allpixels[i] = Color.alpha(Color.TRANSPARENT);
     }

      myBitmap.setPixels(allpixels, 0, myBitmap.getWidth(), 0, 0, myBitmap.getWidth(), myBitmap.getHeight());
      return myBitmap;
}

The above code will take a Bitmap, and return a Bitmap where every pixel which the color is transparentColor is transparent. This works in API as low as level 8, and I have not tested it in any lower.

I typically use something like Color.RED to make my transparent pixels, because I don't use a lot of RED in my assets, but if I do it's a custom red color.

Try this. Also note that setAlpha is in 0-255 range

//bmp is your Bitmap object

BitmapDrawable bd = new BitmapDrawable(bmp);
bd.setAlpha(50);

ImageView v = (ImageView) findViewById(R.id.image);
v.setImageDrawable(bd);

try this,

newBitmap.setImageResource(android.R.color.transparent);
luckyhandler

@akaya's answer is the right way except that the constructor is deprecated. The new way since API 4 would be to use:

BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
drawable.setAlpha(100);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!