編輯:Android 開發實例
直接用 ImageView 顯示 Bitmap 會佔用大量資源,尤其是遇到大尺寸圖片時,稍不留神就可能引發內存溢出(OOM)而導致崩潰。要破解這個難題,關鍵在於對圖片進行合理的降採樣。
BitmapFactory.Options 中的 inSampleSize 屬性能有效降低對系統資源的需求。它的含義是「縮略圖大小為原始圖片的幾分之一」——若設為 2,則取出的縮略圖寬高都是原圖的 1/2,佔用的內存便降為原圖的 1/4。
而另一個屬性 inJustDecodeBounds 則是優化計算的關鍵。SDK 文檔是這樣描述的:
If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.
通俗地說,將它設為 true 後,我們可以在不解碼像素、不佔用內存的前提下,先行讀取到圖片的原始寬高(outHeight 與 outWidth),進而計算出合適的 inSampleSize 縮放值。
布局文件 main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<ImageView
android:id="@+id/imageview"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center" />
</LinearLayout>
核心的 Java 代碼:
public class AndroidImage extends Activity {
private String imageFile = "/sdcard/AndroidSharedPreferencesEditor.png";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView myImageView = (ImageView) findViewById(R.id.imageview);
Bitmap bitmap;
float imagew = 300;
float imageh = 300;
BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();
bitmapFactoryOptions.inJustDecodeBounds = true;
bitmap = BitmapFactory.decodeFile(imageFile, bitmapFactoryOptions);
int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight / imageh);
int xRatio = (int) Math.ceil(bitmapFactoryOptions.outWidth / imagew);
if (yRatio > 1 || xRatio > 1) {
if (yRatio > xRatio) {
bitmapFactoryOptions.inSampleSize = yRatio;
} else {
bitmapFactoryOptions.inSampleSize = xRatio;
}
} else {
// inSampleSize = 1
}
bitmapFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(imageFile, bitmapFactoryOptions);
myImageView.setImageBitmap(bitmap);
}
}
整個邏輯可謂一氣呵成:先「只讀尺寸不解碼」拿到原圖寬高,算出縮放比,再關掉 bounds 模式正式解碼。如此一來,即便原圖再大,也能被馴服在可接受的内存範圍內。
Android Canvas 繪圖透解:MaskFilter 模糊陰影與浮雕效果(附源碼)
本文聚焦一個既實用又有趣的繪圖技巧——如何借助 MaskFilter 為圖形加上模糊陰影與浮雕立體效果。先理清一個概念:Canvas 上的各種 drawXXX 方法決定了
Android 音頻錄製與音頻視覺化開發案例
Android 提供多種音頻處理方式,從呼叫系統內建錄音程式,到自行使用 MediaRecorder、AudioRecord 進行即時聲波分析,都能延伸出不同的應用。本文
Android 登入功能實作範例
登入畫面幾乎是每一款需要帳號的應用必備的環節,它透過詢問使用者的帳號與密碼來完成身分驗證,無論是登入 Facebook、微博還是自家服務都離不開它。 本章將說明如何打造一
Android 理財 App 實作(五):用 ListView 把 SQLite 帳單讀回來
前面幾篇已經把每個月的收支明細寫進 SQLite 資料表了,這一篇要解決的是反過來的問題:怎麼把資料從資料表裡撈出來,攤成一個看得懂的帳單明細畫面。 為什麼最後選了