4

我想用黑白 alpha 蒙版屏蔽位图。我的蒙版图像是黑白的,黑色区域表示透明,白色区域表示不透明。

我需要的是: 当我使用此遮罩图像遮盖任何其他图像时,如果遮罩图像的相应区域为黑色,则结果图像的区域应该是透明的。否则结果图像的区域应该是不透明的。

我附上了示例图像。请帮我解决这些问题。

示例图像: 用于掩蔽的示例图像

到目前为止我所尝试的: 以下方法工作正常。但是它们非常慢。我需要一些在速度和内存方面比这些方法更有效的解决方案。

  • 第一种方法:

      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;
    
4

0 回答 0