android - 如何使位图透明?

标签 android bitmap imageview opacity transparent

/**
 * @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?

最佳答案

// 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 的每个像素都是透明的。这适用于低至 8 级的 API,我还没有在任何更低级别测试过它。

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

关于android - 如何使位图透明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15084128/

相关文章:

android - 定义要查看的顶部和底部阴影

java - Android:类中的 SharedPreferences PreferenceManager.getDefaultSharedPreferences

c# Bitmap.Save 透明度不保存在 png 中

android - ImageView setMargins 不起作用

android - 创建覆盖 ImageView 动画谷歌地图

android - APDU 写命令导致 6A 81

android - android 上的远程 akka Actor ?

Android:如何使用大量的Bitmaps?

c++ - 在 StaticBitmap wxWidgets 上更改图像

java - 如何在 javafx 中调整 imageview 图像的大小?