Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 如何將兩張 Bitmap 合並為一張

編輯:關於 Android 程式設計

在影像處理的開發中,常需要把前景圖疊加在背景圖上合並成一張。做法是建立一張與背景同尺寸的新 Bitmap,再用 Canvas 依序畫上背景與置中的前景:

public static Bitmap combineBitmap(Bitmap background, Bitmap foreground) {
  if (background == null) {
    return null;
  }
  int bgWidth = background.getWidth();
  int bgHeight = background.getHeight();
  int fgWidth = foreground.getWidth();
  int fgHeight = foreground.getHeight();
  Bitmap newmap = Bitmap.createBitmap(bgWidth, bgHeight, Config.ARGB_8888);
  Canvas canvas = new Canvas(newmap);
  canvas.drawBitmap(background, 0, 0, null); // 先畫背景
  // 將前景置中繪製
  canvas.drawBitmap(foreground, (bgWidth - fgWidth) / 2,
    (bgHeight - fgHeight) / 2, null);
  canvas.save(Canvas.ALL_SAVE_FLAG);
  canvas.restore();
  return newmap;
}

關鍵在於:新 Bitmap 以背景的尺寸與 ARGB_8888 建立,先將背景從原點畫上,再透過 (bgWidth - fgWidth) / 2 與 (bgHeight - fgHeight) / 2 的計算,把前景圖置中疊加。這樣就能得到一張前景居中、背景完整的合並圖。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved