Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 實現拍照、相冊選圖並裁剪圖片的完整方案

編輯:Android 開發實例

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

一、效果預覽

先看看最终实现的效果:

二、uCrop 項目應用

裁剪部分採用 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;

七、使用 Crop 裁剪圖片

無論拍照還是選圖,最後都交由 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);
    }
});

透過合理的封裝與基類抽取,拍照、選圖、裁剪這套繁瑣流程就能變得異常簡潔,輕鬆複用到各個專案中。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved