編輯:關於 Android 程式設計
ImageView 是最基礎的圖片展示控件,而它背後真正幹活的是 BitmapFactory。本文整理兩種常見的圖片來源,以及必須掌握的採樣參數。
ImageView images = (ImageView) findViewById(R.id.imageview1); InputStream is = this.getResources().openRawResource(R.drawable.test2); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = false; options.inSampleSize = 10; // 寬高均縮為原圖的 1/10 Bitmap btp = BitmapFactory.decodeStream(is, null, options); images.setImageBitmap(btp);
ImageView images = (ImageView) findViewById(R.id.imageview1); String path = "/storage/sdcard/images/test2.jpg"; BitmapFactory.Options option = new BitmapFactory.Options(); option.inSampleSize = 4; // 縮為原圖的 1/4 Bitmap bm = BitmapFactory.decodeFile(path, option); images.setImageBitmap(bm);
獲取外部存儲根目錄的推薦寫法(避免硬編碼路徑):
String path = Environment.getExternalStorageDirectory() + "/";
同時需要在清單文件中聲明讀取外部存儲的權限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
inSampleSize 是控制內存占用的核心參數,但有幾點必須清楚:
要在不讀取像素的前提下拿到圖片尺寸,先把 inJustDecodeBounds 設為 true:
private Bitmap decodeSampledBitmapFromResource(int resId, int reqWidth,
int reqHeight) {
// 第一遍:只讀邊界
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), resId, options);
// 計算合適的採樣率
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 第二遍:真正解碼
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(getResources(), resId, options);
}
private int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
這個「兩遍解碼」模式是官方推薦的做法,能避免直接加載大圖導致的 OutOfMemoryError。用在 ListView 中時,reqWidth/reqHeight 傳入 ImageView 的實際顯示尺寸即可,通常能節省幾倍的內存。
recycle()(4.4 之前尤其重要)。getExternalStorageDirectory() 路徑訪問共享存儲的圖片會失敗,需改用 MediaStore 或 SAF。
限制 EditText 的輸入字符:禁止中文、只允許字母數字的幾種做法
只允許 EditText 輸入數字或 email 格式字符,官方文檔裡有現成方案,非常簡單。要限制成自定義的數字字符集合也不難,setKeyListener(KeyLis
一個遊戲角色的例子,讓你徹底看懂裝飾者模式
為什麼不從定義講起 設計模式的定義往往抽象到難以理解,讀完還是不知道何時該用。這些模式的誕生,其實都是前輩在實作時撞到了同一堵牆,才總結出的解法。所以本篇換個方式:先讓你
高仿微信 5.2.1 主介面:ViewPager、Fragment 與未讀紅點
這篇文章以模仿微信 5.2.1 主介面為例,說明如何製作自訂標題欄、分頁切換、滑動指示條與未讀訊息紅點。雖然是入門級 Demo,但涵蓋了 ViewPager、Fragme
Android App 整合 Mob 簡訊驗證碼:從申請到無 GUI 接入
為什麼選擇 Mob 簡訊驗證碼許多 App 在註冊、登入或通知時都需要簡訊能力。對個人開發者或小團隊而言,自行接電信服務成本較高,Mob 提供的簡訊驗證碼 SDK 是一個