【问题标题】:How to use Canvas for merging two images in Android?如何使用 Canvas 在 Android 中合并两个图像?
【发布时间】:2011-12-07 21:14:57
【问题描述】:

我想通过重叠创建一个包含两个不同图像的组合图像。

为此我的代码是

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

case 1 :overlay 方法在这种情况下返回 null。

案例 2:但是当我切换图像时,我使用背景图像设置前景,使用前景图像设置背景,然后代码可以正常工作。

但我希望第一个案例应该正常工作,但事实并非如此。 我不明白为什么会这样。

请帮忙

【问题讨论】:

  • 我不知道为什么,现在它正在工作。

标签: android canvas bitmap


【解决方案1】:

我认为它会发生,因为第二个位图的尺寸更大。所以试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 2016-01-19
    相关资源
    最近更新 更多