編輯:Android 開發實例
「更換頭像」幾乎是每個 App 的必備功能,而它背後往往涉及拍照、從相冊選圖、裁剪等一系列操作。本文將帶你封裝一個可複用的 PictureSelectFragment,把這整套流程優雅地實現出來。
先看看最终实现的效果:


裁剪部分採用 Yalantis/uCrop,它的效果相當炫。由於原專案在自定義界面方面略有限制,筆者在其基礎上改造出 Android-Crop,把界面定制獨立出來供用戶自由設置。下圖是模仿微信風格的選圖裁剪 Demo:

整體流程分兩條線:一是選擇設備圖片裁剪並保存到指定路徑;二是調用系統拍照,把照片存到 SD 卡,再裁剪並保存。流程圖如下:

這裡用 PopupWindow 實現底部的選擇框,提供「拍照」「從相冊選擇」「取消」三個選項:

XML 佈局用 LinearLayout 豎向排列三個按鈕:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical">
<LinearLayout
android:id="@+id/pop_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#444"
android:gravity="center_horizontal"
android:orientation="vertical">
<Button android:id="@+id/picture_selector_take_photo_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="10dp"
android:background="#4d69ff"
android:padding="10dp"
android:text="拍照"
android:textColor="#CEC9E7"
android:textSize="18sp" />
<Button android:id="@+id/picture_selector_pick_picture_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="5dp"
android:background="#4d69ff"
android:padding="10dp"
android:text="從相冊選擇"
android:textColor="#CEC9E7"
android:textSize="18sp" />
<Button android:id="@+id/picture_selector_cancel_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:layout_marginTop="20dp"
android:background="@android:color/white"
android:padding="10dp"
android:text="取消"
android:textColor="#373447"
android:textSize="18sp" />
</LinearLayout>
</RelativeLayout>
透過一個選擇監聽接口把點擊事件回調出去,讓調用方自由處理:
public interface OnSelectedListener {
void OnSelected(View v, int position);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.picture_selector_take_photo_btn:
if (null != mOnSelectedListener) mOnSelectedListener.OnSelected(v, 0);
break;
case R.id.picture_selector_pick_picture_btn:
if (null != mOnSelectedListener) mOnSelectedListener.OnSelected(v, 1);
break;
case R.id.picture_selector_cancel_btn:
if (null != mOnSelectedListener) mOnSelectedListener.OnSelected(v, 2);
break;
}
}
調用系統相機拍照,並透過 MediaStore.EXTRA_OUTPUT 指定照片存儲路徑:
case 0: // "拍照"按鈕被點擊
mSelectPicturePopupWindow.dismissPopupWindow();
Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mTempPhotoPath)));
startActivityForResult(takeIntent, CAMERA_REQUEST_CODE);
break;
其中 mTempPhotoPath 指定為 SD 卡根目錄下的 photo.jpeg。拍照完成後會回調到 onActivityResult。
調用系統的圖片選擇器,並可透過 setDataAndType 限制圖片類型:
case 1: // "從相冊選擇"按鈕被點擊
mSelectPicturePopupWindow.dismissPopupWindow();
Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(pickIntent, GALLERY_REQUEST_CODE);
break;
無論拍照還是選圖,最後都交由 UCrop 裁剪。這裡設定寬高比 1:1、最大尺寸 512×512,可依需求調整:
public void startCropActivity(Uri uri) {
UCrop.of(uri, mDestinationUri)
.withAspectRatio(1, 1)
.withMaxResultSize(512, 512)
.withTargetActivity(CropActivity.class)
.start(mActivity, this);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == mActivity.RESULT_OK) {
switch (requestCode) {
case CAMERA_REQUEST_CODE:
File temp = new File(mTempPhotoPath);
startCropActivity(Uri.fromFile(temp));
break;
case GALLERY_REQUEST_CODE:
startCropActivity(data.getData());
break;
case UCrop.REQUEST_CROP:
// 裁剪成功
break;
case UCrop.RESULT_ERROR:
// 裁剪失敗
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
CropActivity 的界面如下,可自由定製:

經過改造,也能輕鬆設計成下面兩種風格:


裁剪的核心在於 CropView 的配置,例如是否允許縮放、是否顯示網格、外部陰影顏色等:
@Override
protected void initViews() {
initToolBar();
mGestureCropImageView = mUCropView.getCropImageView();
mOverlayView = mUCropView.getOverlayView();
mGestureCropImageView.setScaleEnabled(true); // 允許縮放
mGestureCropImageView.setRotateEnabled(false); // 禁止旋轉
mOverlayView.setDimmedColor(Color.parseColor("#AA000000"));
mOverlayView.setOvalDimmedLayer(false); // 矩形遮罩
mOverlayView.setShowCropFrame(true); // 顯示裁剪邊框
mOverlayView.setShowCropGrid(false); // 不顯示網格
setImageData(getIntent());
}
最關鍵的是裁剪並保存圖片的環節:
private void cropAndSaveImage() {
OutputStream outputStream = null;
try {
final Bitmap croppedBitmap = mGestureCropImageView.cropImage();
if (croppedBitmap != null) {
outputStream = getContentResolver().openOutputStream(mOutputUri);
croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 85, outputStream);
croppedBitmap.recycle();
setResultUri(mOutputUri, mGestureCropImageView.getTargetAspectRatio());
finish();
}
} catch (Exception e) {
setResultException(e);
finish();
} finally {
BitmapLoadUtils.close(outputStream);
}
}
最後,透過一個 OnPictureSelectedListener 回調接口,把裁剪結果(Uri 與 Bitmap)交給調用方。經過上述封裝,業務代碼只需繼承 PictureSelectFragment,幾行就能搞定頭像更換:
mPictureIv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectPicture();
}
});
setOnPictureSelectedListener(new OnPictureSelectedListener() {
@Override
public void onPictureSelected(Uri fileUri, Bitmap bitmap) {
mPictureIv.setImageBitmap(bitmap);
}
});
透過合理的封裝與基類抽取,拍照、選圖、裁剪這套繁瑣流程就能變得異常簡潔,輕鬆複用到各個專案中。
Android MediaPlayer 深度說明:音訊播放控制與播放器範例
Android 提供多種播放音訊與影片的方式,而其中最廣為使用的莫過於 MediaPlayer 類別。它代表系統內建媒體播放服務的用戶端介面,能處理本機檔案、網路串流,音
Android 應用程式簽名步驟與相關知識
Android 要求每個應用程式都必須經過數字簽名才能安裝。簽名的作用不是決定使用者可以安裝哪些應用程式,而是用來標識作者並在應用程式之間建立信任關係。為什麼需要簽名開發
Android JSON 解析:以 JSONObject 擷取網路資料
JSON(JavaScript Object Notation)是一種與語言無關的資料交換格式,也是 XML 廣受歡迎的替代方案。本章說明如何在 Android 中解析
Android 基礎:使用 Fragment 適配不同螢幕與解析度
最近工作繁忙,一個新專案急著上線,很多功能都得重做,一直在寫程式、Debug。今天因為新程式要用 Fragment 來做,雖然以前用過,但沒有仔細研究,於是趁機寫篇文章記