android studio |在图像上将特定颜色设置为透明

时间:2017-12-09 17:14:41

标签: android image android-layout

我的目标是让图片上的特定颜色透明,就像在游戏中一样,在加载时忽略一个普通的背景颜色。

我读过的内容

  1. Draw a Bitmap on a Canvas replacing Black Pixels to Transparent
  2. Replacing a color in a Bitmap
  3. How to change colors of a Drawable in Android?
  4. Android: Make specific (green) color in background image transparent
  5. Android how to apply mask on ImageView?
  6. 我添加的代码是默认的.java

    ImageView log = (ImageView) findViewById(R.id.iconLogo);
    int col = ResourcesCompat.getColor(getResources(), R.color.colorTrans, null);
    log.getDrawable().mutate().setColorFilter(col, PorterDuff.Mode.SRC_IN);
    //log.getDrawable().setColorFilter(col, PorterDuff.Mode.SRC_IN); //take2
    //log.setColorFilter(R.color.colorTrans, PorterDuff.Mode.SRC_IN); //take3
    

    使图像可变提供更好的结果,但仍然不会从图像中减去R.color.colorTrans。总体而言,在使用过滤器后,它似乎在整个图像上方作为过滤器工作,并且没有搜索我设置的颜色,因此颜色始终存在并且不排除不依赖于使用的模式。

    第二个选项

     public static Bitmap getBitmapWithTransparentBG(Bitmap srcBitmap, int BgColor) {
            Bitmap result = srcBitmap.copy(Bitmap.Config.ARGB_8888, true);
            int nWidth = result.getWidth();
            int nHeight = result.getHeight();
            for (int y = 0; y < nHeight; ++y)
                for (int x = 0; x < nWidth; ++x) {
                    int nPixelColor = result.getPixel(x, y);
                    if (nPixelColor == BgColor)
                        result.setPixel(x, y, Color.TRANSPARENT);
                }
            return result;
        }
    

    仅使用一个600x600 px png文件可将应用程序加载时间从1-2秒增加到8-12秒,而且不会删除特定颜色。因此不能用于多个igames。

    我需要的是从ImageView中的Image中删除/忽略特定颜色,而不是使所有图片透明。由于游戏使用没有alpha的平铺地图,因此必须有一种方法可以在不添加alpha遮罩的情况下进行操作。

1 个答案:

答案 0 :(得分:0)

这里的解决方案unable to transparent pixels of a bitmap image

然而,即使在一张照片上使用它也会大大增加加载时间。可能.png已经清除背景可能会更好用。