android – 如何使位图透明?

/**
 * @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 : https://*.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,我使ImageView的Bitmap是半透明的.

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

然而,Imageview在不是白色之前显示更多的暗色.如何使用位图制作半透明(白色背景)Imageview?

解决方法:

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

上面的代码将采用Bitmap,并返回一个Bitmap,其中颜色为transparentColor的每个像素都是透明的.这适用于API低至8级,我没有在任何更低的测试.

我通常使用像Color.RED这样的东西来制作我的透明像素,因为我的资产中没有使用很多RED,但如果我这样做是自定义的红色.

上一篇:Android eclipse将压缩状态添加到ImageView


下一篇:android – 如何在imageview中显示外部存储图像