在Android中使用黑白alpha蒙版进行高效的位图屏蔽

时间:2013-06-19 07:49:10

标签: android bitmap alpha masking

我想用黑白alpha蒙版掩盖一个Bitmap。我的蒙版图像是黑白的,黑色区域表示透明,白色区域表示OPAQUE。

我需要的是: 当我使用此蒙版图像来遮盖任何其他图像时,如果蒙版图像的相应区域是黑色,则所得图像的区域应该是透明的。否则,结果图像的区域应该是OPAQUE。

我附上了样本图片。请帮帮我这个家伙。

示例图片 Sample Image for Masking

到目前为止我尝试了什么: 以下方法工作正常。但它们很慢。我需要一些比速度和内存更有效的解决方案。

  • 第一种方法:

      int width = rgbDrawable.getWidth();
      int height = rgbDrawable.getHeight();
    
      if (width != alphaDrawable.getWidth() || height != alphaDrawable.getHeight()) {
        throw new IllegalStateException("image size mismatch!");
      }
    
      Bitmap destBitmap = Bitmap.createBitmap(width, height,
          Bitmap.Config.ARGB_8888);
    
      int[] pixels = new int[width];
      int[] alpha = new int[width];
    
      for (int y = 0; y < height; y++)
      {
          rgbDrawable.getPixels(pixels, 0, width, 0, y, width, 1);
          alphaDrawable.getPixels(alpha, 0, width, 0, y, width, 1);
    
          for (int x = 0; x < width; x++) 
          {
              // Replace the alpha channel with the r value from the bitmap.
              pixels[x] = (pixels[x] & 0x00FFFFFF) | ((alpha[x] << 8) & 0xFF000000);
          }
    
        destBitmap.setPixels(pixels, 0, width, 0, y, width, 1);
      }
    
      alphaDrawable.recycle();
      rgbDrawable.recycle();
    
      return destBitmap;
    
  • 第二种方法

        float[] nlf =  new float[] {
                                0, 0, 0, 0, 0,
                                0, 0, 0, 0, 0,
                                0, 0, 0, 0, 0,
                                1, 0, 0, 0, 0};
    
    ColorMatrix sRedToAlphaMatrix = new ColorMatrix(nlf);
    
    ColorMatrixColorFilter sRedToAlphaFilter = new ColorMatrixColorFilter(sRedToAlphaMatrix);
    
    // Load RGB data
    Bitmap rgb = rgbDrawable;
    
    // Prepare result Bitmap
    Bitmap target = Bitmap.createBitmap(rgb.getWidth(), rgb.getHeight(), Bitmap.Config.ARGB_8888);
    
    Canvas c = new Canvas(target);
    c.setDensity(Bitmap.DENSITY_NONE);
    
    // Draw RGB data on our result bitmap
    c.drawBitmap(rgb, 0, 0, null);
    
    // At this point, we don't need rgb data any more: discard!
    rgb.recycle();
    rgb = null;
    
    // Load Alpha data
    Bitmap alpha = alphaDrawable;
    
    // Draw alpha data on our result bitmap
    final Paint grayToAlpha = new Paint();
    grayToAlpha.setColorFilter(sRedToAlphaFilter);
    grayToAlpha.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
    c.drawBitmap(alpha, 0, 0, grayToAlpha); 
    
    // Don't need alpha data any more: discard!
    alpha.recycle();
    alpha = null;
    
    return target;
    

0 个答案:

没有答案