2013-02-26 145 views
2
/** 
* @param bitmap 
*   The source bitmap. 
* @param opacity 
*   a value between 0 (completely transparent) and 255 (completely 
*   opaque). 
* @return The opacity-adjusted bitmap. If the source bitmap is mutable it 
*   will be adjusted and returned, otherwise a new bitmap is created. 
*   Source : http://stackoverflow.com/questions/7392062/android- 
*   semitransparent-bitmap-background-is-black/14858913#14858913 
*/ 
private Bitmap adjustOpacity(Bitmap bitmap, int opacity) { 
    Bitmap mutableBitmap = bitmap.isMutable() ? bitmap : bitmap.copy(Bitmap.Config.ARGB_8888, true); 
    Canvas canvas = new Canvas(mutableBitmap); 
    int colour = (opacity & 0xFF) << 24; 
    canvas.drawColor(colour, PorterDuff.Mode.DST_IN); 
    return mutableBitmap; 
} 

使用adjustOpacity,我讓ImageViewBitmap是半透明的。如何使位圖透明?

Bitmap newBitmap = adjustOpacity(orignalBitmap, 10); 
view.setImageBitmap(newBitmap); 
view.setBackgroundColor(Color.WHITE); 

但是,Imageview顯示更加黑暗之前不是白色。如何使用Bitmap製作半透明(白色背景)Imageview?

回答

0

試試這個,

newBitmap.setImageResource(android.R.color.transparent); 
+1

你的意思 view.setImageResource(android.R.color.transparent); – vingorius 2013-02-26 08:19:09

1

試試這個。還要注意的是setAlpha是在0-255範圍

//bmp is your Bitmap object 

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

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

謝謝,我的意思是,我想改變位圖本身! – vingorius 2013-02-28 08:21:28

+0

@vingorius您應該更改問題標題,然後 – akaya 2013-02-28 13:09:41

+0

謝謝@kaya,我會的。 – vingorius 2013-03-04 02:37:55

6
// 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; 
} 

上面的代碼將採取一個位圖,並返回一個位圖,其中每一個所述顏色是transparentColor像素是透明的。這在低至8級的API中工作,並且我還沒有在任何更低的級別上進行測試。

我通常使用類似Color.RED的東西來製作我的透明像素,因爲我的資產中沒有使用大量的紅色,但是如果我這樣做是自定義的紅色。

0

@ akaya的答案是正確的方式,除了構造函數已被棄用。因爲API 4的新方法是使用:

BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap); 
drawable.setAlpha(100);