編輯:關於 Android 程式設計
本文示範如何拍照後進行裁剪。先看效果:

拍照截圖有個先天限制:現在手機鏡頭动辄數百萬畫素,拍出的原始圖非常大。若沿用相冊那套「小圖用 Bitmap 回傳」的做法,極易撞上 TransactionTooLargeException 或 Bundle 大小上限。因此拍照場景不論大小圖,一律用 Uri 操作。
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
使用 MediaStore.ACTION_IMAGE_CAPTURE 就能叫起相機程式,並用 EXTRA_OUTPUT 指定照片寫去哪裡。
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, TAKE_BIG_PICTURE);//or TAKE_SMALL_PICTURE
switch (requestCode) { case TAKE_BIG_PICTURE: Log.d(TAG, "TAKE_BIG_PICTURE: data = " + data);//it seems to be null //TODO sent to crop cropImageUri(imageUri, 800, 400, CROP_BIG_PICTURE); break; case TAKE_SMALL_PICTURE: Log.i(TAG, "TAKE_SMALL_PICTURE: data = " + data); //TODO sent to crop cropImageUri(imageUri, 300, 150, CROP_SMALL_PICTURE); break; default: break; }
不論大圖小圖,傳的都是 Uri,只有輸出尺寸不同。把共同邏輯抽成一個方法:
private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode){ Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", 2); intent.putExtra("aspectY", 1); intent.putExtra("outputX", outputX); intent.putExtra("outputY", outputY); intent.putExtra("scale", true); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); intent.putExtra("return-data", false); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); // no face detection startActivityForResult(intent, requestCode); }
switch (requestCode) { case CROP_BIG_PICTURE://from crop_big_picture Log.d(TAG, "CROP_BIG_PICTURE: data = " + data);//it seems to be null if(imageUri != null){ Bitmap bitmap = decodeUriAsBitmap(imageUri); imageView.setImageBitmap(bitmap); } break; case CROP_SMALL_PICTURE: if(imageUri != null){ Bitmap bitmap = decodeUriAsBitmap(imageUri); imageView.setImageBitmap(bitmap); }else{ Log.e(TAG, "CROP_SMALL_PICTURE: data = " + data); } break; default: break; }
兩個實務提醒:一是 com.android.camera.action.CROP 屬於非公開的隱式 Intent,各廠牌實作差異大,記得做版本與機型相容處理;二是別忘了在 Manifest 加上寫入外部儲存的權限,Android 6.0 以上還要動態申請。掌握「一律走 Uri」這個原則,拍照截圖的記憶體風險就能大幅降低。
Android 刮刮卡效果實作解析
刮刮卡效果原理 刮刮卡效果的核心是「底圖加上可刮除的遮罩層」。底層顯示獎項或圖片,上層蓋著灰色遮罩。當使用者用手指滑動時,遮罩會沿著手勢路徑被刮開,露出底圖。 Xfer
Android 性能優化:Understanding Overdraw 過度繪製的排查與治理
什麼是過度繪製 Overdraw 指的是在一幀渲染時間內,同一個像素被反覆繪製多次。理論上一個像素只畫一次是最優的,但層層嵌套的布局會導致部分像素被覆蓋重畫,而每一次繪製
Android 添加新視頻格式:媒體庫掃描實踐
需求很明確:讓 MediaProvider 數據庫能夠識別並收錄 .mov 後綴格式的視頻文件。本文記錄一次完整的源碼改動過程。 首先需要摸清 .mov 文件的編碼格式。
Android快速入門:新手必須掌握的核心基礎知識
這是一篇面向初學者的Android入門教程,從搭建環境出發,一路涵蓋四大組件、UI布局、數據存儲、消息機制、事件處理、動畫與圖像處理等核心知識,幫你快速建立完整的知識地圖