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

Android 圖片拆分完整示例:把一張 Bitmap 切成九宮格

編輯:關於 Android 程式設計

把一張圖片切成多塊,常用於拼圖遊戲、九宮格選單或大圖分塊載入。核心只有一個 API:Bitmap.createBitmap 的裁剪版本,傳入原圖與要裁出的矩形區域即可。

版面配置

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/splitButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dip"
        android:text="拆分圖片" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/e" />
</RelativeLayout>

拆分邏輯

/**
 * @param rawBitmap 原始圖片
 * @param row       切成幾列
 * @param column    切成幾欄
 */
private ArrayList<Bitmap> splitImage(Bitmap rawBitmap, int row, int column) {
    ArrayList<Bitmap> partImages = new ArrayList<Bitmap>(row * column);

    int rawWidth  = rawBitmap.getWidth();
    int rawHeight = rawBitmap.getHeight();

    // 每一小塊的寬高(以整數除法求得)
    int perPartWidth  = rawWidth  / column;
    int perPartHeight = rawHeight / row;

    for (int i = 0; i < row; i++) {
        for (int j = 0; j < column; j++) {
            int x = j * perPartWidth;    // 左上角 x 座標
            int y = i * perPartHeight;   // 左上角 y 座標
            Bitmap part = Bitmap.createBitmap(rawBitmap, x, y, perPartWidth, perPartHeight);
            partImages.add(part);
        }
    }
    return partImages;
}

Activity 中的串接

public class MainActivity extends Activity {

    private Button mSplitButton;
    private ImageView mImageView;
    private Bitmap mRawBitmap;
    private int row = 3;
    private int column = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mSplitButton = (Button) findViewById(R.id.splitButton);
        mImageView   = (ImageView) findViewById(R.id.imageView);
        mRawBitmap   = BitmapFactory.decodeResource(getResources(), R.drawable.e);

        mSplitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<Bitmap> parts = splitImage(mRawBitmap, row, column);
                mImageView.setImageBitmap(null);   // 清空原圖
                // 此處可將 parts 逐塊顯示或另存為檔案
            }
        });
    }
}

幾個實務上的注意點

整數除法會有餘數:若原圖寬高不能被欄數、列數整除,最後一塊會略有誤差。若要求嚴絲合縫,可在最後一欄/列時用原圖寬高減去已用掉的長度來補齊。

createBitmap 回傳的是新 Bitmap:它與原圖共用同一份像素記憶體,因此不會額外複製資料,記憶體開銷小;但相對地,只要你回收原圖,這些子圖也會失效。

記得回收:切完不再使用的 Bitmap 應呼叫 recycle(),尤其在 Activity 銷毀時,避免 OOM。

大圖先降採樣:decodeResource 時可透過 BitmapFactory.Options 的 inSampleSize 先做縮放,否則解一張高解析照片就可能直接記憶體不足。

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