編輯:關於 Android 開發
直接使用 ImageView 顯示 bitmap 會佔用較多資源,特別是在圖片較大時,甚至可能導致程式崩潰。因此,對 Bitmap 進行優化是應用開發中不可忽略的一環。
透過 BitmapFactory.Options 設定 inSampleSize,可以有效降低對系統資源的需求。inSampleSize 表示縮圖大小為原始圖片的幾分之一:若此值為 2,則取出的縮圖寬與高都是原始圖片的 1/2,圖片大小便縮為原始的 1/4。
Options 中還有一個屬性 inJustDecodeBounds。SDK 對它的說明是:若設為 true,解碼器會回傳 null(不產生 bitmap),但 out... 相關欄位仍會被設定,讓呼叫端得以在不配置像素記憶體的情況下查詢圖片資訊。
因此,我們可以先將 inJustDecodeBounds 設為 true,取得 outHeight(原始高度)與 outWidth(原始寬度),再據此計算出一個合理的 inSampleSize 縮放值。
<?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>
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;
public class AndroidImage extends Activity {
private String imageFile = "/sdcard/AndroidSharedPreferencesEditor.png";
/** Called when the activity is first created. */
@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;
Toast.makeText(this, "yRatio = " + String.valueOf(yRatio), Toast.LENGTH_LONG).show();
} else {
bitmapFactoryOptions.inSampleSize = xRatio;
Toast.makeText(this, "xRatio = " + String.valueOf(xRatio), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "inSampleSize = 1", Toast.LENGTH_LONG).show();
}
bitmapFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(imageFile, bitmapFactoryOptions);
myImageView.setImageBitmap(bitmap);
}
}
透過「先量測、後縮放」的兩段式解碼策略,能在顯示大圖時大幅降低記憶體佔用,有效避免 OutOfMemoryError 造成的崩潰。
10 個值得收藏的 Android 開發學習網站
10 個值得收藏的 Android 開發學習網站 學習 Android 開發,除了官方文件,網路上其實還有不少優質資源。以下依序整理十個我認為值得放進書籤的網站,從入門教
騰訊 Bugly 乾貨:RxJava 結合 MVP 的實戰分層與線程調度
本文整理自騰訊 Bugly 開發者社群的技術分享,主講者為騰訊 IEG Android 開發工程師戴俊,主題是《基於 RxJava 的一種 MVP 實現》。 RxJava
Android AsyncTask 使用詳解
Android AsyncTask 使用詳解 在 Android 中,耗時操作不能放在主執行緒,否則容易造成畫面卡頓。AsyncTask 是早期常見的簡便方案,它封裝了
以 Adapter 模式重構 Android 圓形菜單
以 Adapter 模式重構 Android 圓形菜單 圓形菜單這類自訂 UI 很能吸引注意,但真正可維護的關鍵,在於如何隔離變化。本文以重構圓形菜單為例,說明如何透過