現象:在 `ScrollView` 或其子 `Layout` 設定 `android:background="@drawable/large_image"`,App 啟動瞬間崩潰,Logcat 顯示 `OutOfMemoryError`。
背景圖解析度過高(如 3000×4000 px),解碼後佔用記憶體 = 寬 × 高 × 4 bytes ≈ 48 MB,超過單進程記憶體上限(舊設備 16-24 MB,新設備 192-512 MB),且 `ScrollView` 不支援 `android:tileMode` 平鋪,會嘗試一次性載入完整圖片。
// 在 Activity/Fragment onCreate 中
ScrollView scrollView = findViewById(R.id.scrollView);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.bg_image, opts);
// 計算縮放比例,目標寬度 = 螢幕寬度
opts.inSampleSize = calculateInSampleSize(opts, screenWidth, 0);
opts.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg_image, opts);
scrollView.setBackground(new BitmapDrawable(getResources(), bitmap));
<bitmap xmlns:android="https://schemas.android.com/apk/res/android"
android:src="@drawable/small_pattern"
android:tileMode="repeat"
android:dither="true" />
在 `ScrollView` 設定 `android:background="@drawable/tiled_bg"`,記憶體佔用極小。
將大圖切割為多張小圖,使用 `RecyclerView` + `GridLayoutManager` 惰性載入,或使用 Subsampling Scale Image View 庫。
Glide/Picasso 載入網路圖片時自動縮放至 `ImageView` 尺寸。Android Profiler → Memory 檢查 Bitmap 記憶體佔用。核心原則:背景圖解析度不超過螢幕解析度,優先使用可平鋪小圖或程式碼縮放載入。