【问题标题】:Canvas shows transparent part of bitmap in black color - Android画布以黑色显示位图的透明部分 - Android
【发布时间】:2025-12-10 23:50:01
【问题描述】:

在我的 android 应用程序中,我想绘制两个图像 - img1 和 img2。首先,我会在Canvas 上绘制img2。之后,我将在Canvas 上绘制 img1,这将与 img2 重叠。 Img1 包含透明部分。问题是,img1 的透明部分显示为黑色,但我希望 img2 通过 img1 的透明部分可见。我无法做到这一点。 请帮我解决这个问题。 谢谢。

代码:

protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Bitmap b = BitmapFactory.decodeResource(getResources(),
                R.drawable.white_bg);    //img2
        canvas.drawBitmap(b, 0, 0, null);
        canvas.save();

        canvas.drawBitmap(realImage, 0, 0, null);  //img1
    }

【问题讨论】:

    标签: android bitmap android-canvas android-view ondraw


    【解决方案1】:

    加载位图后尝试bitmap.setHasAlpha(true)

    【讨论】:

      【解决方案2】:

      在对我的代码进行一些修改后,我得到了输出。这是我使用的代码。

        public class FrameView extends View{
      
          Bitmap bitmap = null;
      
          public FrameView(Context context) {
                  super(context);
                  this.context = context;
      
              }
      
              public FrameView(Context context, AttributeSet attrs) {
                  super(context, attrs);
                  bitmap = Bitmap.createBitmap(this.screenWidth, this.screenHeight,
                          Bitmap.Config.ARGB_8888);
      
              }
      
              public FrameView(Context context, AttributeSet attrs, int defStyle) {
                  super(context, attrs, defStyle);
                  this.context = context;
              }
      
          @Override
              protected void onDraw(Canvas canvas) {
                  super.onDraw(canvas);
                  if (isTouchGestures) {
                      invalidate();
                      mImgDrawables.get(0).draw(canvas);
                      canvas.drawBitmap(bitmap, 0, 0, null);
                  }
      
              }
      
          //this function is invoked from my activity which is using this view
          public void setFrame(int frame) {
      
                  bitmap = BitmapFactory.decodeStream(getResources().openRawResource(
                          frame));
      
                  bitmap = Bitmap.createScaledBitmap(bitmap, this.screenWidth,
                          this.screenHeight, true);
      
              }
          }
      

      【讨论】:

        【解决方案3】:

        使用 Paint 对象设置透明度的 Alpha 通道。

        Paint alphaChannel = new Paint()
        alphaChannel.setAlpha(100) // set alpha to 100 for complete transparent
        canvas.drawBitmap(b, 0, 0, alphaChannel);
        

        【讨论】:

        • 我试过了,但它使整个位图透明。我希望正确显示位图的透明区域。现在,该区域以黑色显示。
        • 完全透明度来自 0,而不是 100。完全可见性来自 alpha = 255。