編輯:關於 Android 程式設計
專案裡取圖片的地方大致分三類:打包進 APK 的 drawable、放在 assets 的原始檔,以及外部儲存空間的 SD 卡。三者的 API 完全不同,這裡整理成對照表。
這是最常見的做法,用資源 ID 直接換成 Drawable 或 Bitmap。
(1)用 ID 取 Drawable
Drawable drawable = getResources().getDrawable(R.drawable.xxx);
(2)用 ID 取 Bitmap
Resources res = getResources(); Bitmap bitmap = BitmapFactory.decodeResource(res, id);
(3)只知道名稱時,先反查 ID
// name:圖片名稱;defType:資源類型(drawable、string 等);defPackage:專案包名 int id = res.getIdentifier(name, defType, defPackage); Drawable drawable = getResources().getDrawable(id);
assets 裡的檔案沒有資源 ID,得靠 AssetManager 開串流。
AssetManager asm = getAssets(); InputStream is = asm.open(name); // name 為圖片檔名 // 取 Drawable Drawable da = Drawable.createFromStream(is, null); // 取 Bitmap Bitmap bitmap = BitmapFactory.decodeStream(is);
先組出路徑,再交給 BitmapFactory。
String imgFilePath = Environment.getExternalStorageDirectory().toString()
+ "/DCIM/device.png";
(1)走 FileInputStream
FileInputStream fis = new FileInputStream(new File(imgFilePath)); Bitmap bmp = BitmapFactory.decodeStream(fis);
(2)直接用 decodeFile
ImageView iv = (ImageView) findViewById(R.id.image);
Bitmap bit = BitmapFactory.decodeFile("/sdcard/android.bmp");
iv.setImageBitmap(bit);
(3)用 createFromPath 取 Drawable
iv.setImageDrawable(Drawable.createFromPath(
new File(Environment.getExternalStorageDirectory(), "camera.jpg")
.getAbsolutePath()));
實務提醒:讀 SD 卡需要在清單檔宣告 READ_EXTERNAL_STORAGE(Android 6.0 起還要跑-time 權限),而 decode 大圖時記得搭配 BitmapFactory.Options.inSampleSize 做降採樣,否則 OOM 幾乎是必然。
Android 裡那些容易被忽略的 UI 細節:從游標、滾動條到點九圖
做 Android 專案久了會發現,真正拉開產品質感差距的往往不是什麼高階架構,而是一堆不起眼的細節:輸入框游標的顏色、選字時那個小水滴手柄、滾動條的粗細與位置、滑到底部
一步一步實現 Android 自定義組合 View
前言 最近在做一款電商 B 端 App,新版本上線後終於有時間停下來梳理代碼。今天想聊的是自定義 View 裡最容易被低估的一類——組合控件。它不是為了炫技去重寫 onD
React Native 佈局核心:Flexbox 六大屬性圖文全解
寫 React Native 時,很多人從 Android 原生轉過來會有點不適應——這裡沒有 LinearLayout,也沒有 RelativeLayout,取而代之的
Android AIDL 跨進程通信完整指南:從概念到 Android Studio 實操
在 Android 開發裡,「進程」這條看不見的邊界,常常決定了一個功能能不能落地。當你需要讓兩個不同的應用互相調用對方的能力,或者想把耗時任務丟到另一個進程去跑,AID