編輯:關於 Android 程式設計
本篇接續上一篇對拍照截圖的分析,把場景換成「從相冊選圖並裁剪」。先看成品:


依先前的結論,圖片來源有拍照與相冊兩種,而取回資料的方式則有:
Bitmap 有大小上限,尺寸一大就可能拿不到實際解析度。因此這裡採用「大圖用 Uri、小圖用 Bitmap」的雙軌做法。
private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";//temp file Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);//The Uri to store the big bitmap
從相冊選圖的 Action 是 Intent.ACTION_GET_CONTENT。
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 2); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 600); intent.putExtra("outputY", 300); intent.putExtra("scale", true); intent.putExtra("return-data", false); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); // no face detection startActivityForResult(intent, CHOOSE_BIG_PICTURE);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 2); intent.putExtra("aspectY", 1); intent.putExtra("outputX", 200); intent.putExtra("outputY", 100); intent.putExtra("scale", true); intent.putExtra("return-data", true); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); // no face detection startActivityForResult(intent, CHOOSE_SMALL_PICTURE);
兩者的差異只在尺寸與 return-data:大圖設為 false,結果寫入 imageUri 指向的檔案;小圖設為 true,直接從 Intent 回傳。
switch (requestCode) { case CHOOSE_BIG_PICTURE: Log.d(TAG, "CHOOSE_BIG_PICTURE: data = " + data);//it seems to be null if(imageUri != null){ Bitmap bitmap = decodeUriAsBitmap(imageUri);//decode bitmap imageView.setImageBitmap(bitmap); } break; case CHOOSE_SMALL_PICTURE: if(data != null){ Bitmap bitmap = data.getParcelableExtra("data"); imageView.setImageBitmap(bitmap); }else{ Log.e(TAG, "CHOOSE_SMALL_PICTURE: data = " + data); } break; default: break; } private Bitmap decodeUriAsBitmap(Uri uri){ Bitmap bitmap = null; try { bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri)); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } return bitmap; }
要注意的是,各廠牌 ROM 對裁剪 Intent 的支援程度不一,實務上仍需針對主流機型做相容性處理與例外攔截。這套「大圖存 Uri、小圖走 Bundle」的分工,是在記憶體與畫質之間取得平衡的可靠做法。
Android 自訂標題欄背景圖的完整實作教學
想讓 App 的標題欄更有質感?除了單純的純色背景,我們還可以為標題欄設定具有凹凸感的背景圖片。本文將一步步示範如何自訂標題欄背景。 設定標題欄背景 1> 準備背景
打造萬能下拉/上拉刷新框架 XRefreshView(二)
一、前言 上一篇發表之後忙了大半個月,但每天晚上下班後仍持續更新與維護 XRefreshView,也依據一些朋友的回饋修掉了若干問題。這次再寫一篇,是因為它已經走到了功能
Android 網路資料儲存實作:呼叫 WebService 並用 Gson 解析 JSON
什麼是網路儲存 在實際專案中,把資料放在伺服器上的場景非常多。所謂網路儲存,就是資料存在遠端主機,App 端像訪問一個 URL 那樣去取,拿到回應後再解析成物件。雙方通常
Android 禁止 ViewPager 滑動
最近項目中有個需求:禁止 ViewPager 的滑動事件。我們看 360 手機助手的界面,風格大概就是這樣——中間內容是不可滑動的。 下面寫個 demo 說明如何禁止