如何在Android中使用Canvas合并两个图像?

6
我希望通过叠加来创建包含两张不同图片的合成图像。
以下是我的代码:
  ImageView image = (ImageView) findViewById(R.id.imageView1);
  Drawable drawableFore = getResources().getDrawable(R.drawable.foreg);
  Drawable drawableBack = getResources().getDrawable(R.drawable.backg);

  Bitmap bitmapFore = ((BitmapDrawable) drawableFore).getBitmap();
  Bitmap bitmapBack = ((BitmapDrawable) drawableBack).getBitmap();

  Bitmap scaledBitmapFore = Bitmap.createScaledBitmap(bitmapFore, 35, 35, true);
  Bitmap scaledBitmapBack = Bitmap.createScaledBitmap(bitmapBack, 45, 45, true);

  Bitmap combineImages = overlay(scaledBitmapBack, scaledBitmapFore);

  image.setImageBitmap(combineImages);

overlay() 方法是

public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2)
{
 try
 {
   Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(),  bmp1.getConfig());
   Canvas canvas = new Canvas(bmOverlay);
   canvas.drawBitmap(bmp1, new Matrix(), null);
   canvas.drawBitmap(bmp2, 0, 0, null);
   return bmOverlay;
 } catch (Exception e)
 {
    // TODO: handle exception
  e.printStackTrace();
  return null;
 }
}

情况1:在此情况下,覆盖方法返回null。

情况2:但是,当我切换图像时,使用背景图像设置前景并使用前景图像设置背景,则代码可以正常工作。

但我希望第一种情况能够正常工作,但事实并非如此。 我不知道为什么会发生这种情况。

请帮忙解决问题。


我不知道为什么和如何,但现在它可以工作了。 - Arun Badole
1个回答

11

我认为这是发生的原因,因为第二个位图的大小更大。所以尝试这样做:

public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2)
{
 try
 {
   int maxWidth = (bmp1.getWidth() > bmp2.getWidth() ? bmp1.getWidth() : bmp2.getWidth());
   int maxHeight = (bmp1.getHeight() > bmp2.getHeight() ? bmp1.getHeight() : bmp2.getHeight());
   Bitmap bmOverlay = Bitmap.createBitmap(maxWidth, maxHeight,  bmp1.getConfig());
   Canvas canvas = new Canvas(bmOverlay);
   canvas.drawBitmap(bmp1, 0, 0, null);
   canvas.drawBitmap(bmp2, 0, 0, null);
   return bmOverlay;

 } catch (Exception e)
 {
    // TODO: handle exception
  e.printStackTrace();
  return null;
 }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接