天天看點

安卓圖檔裁剪之Android-Image-Cropper簡單使用

圖檔裁剪是一個相對用的比較多的功能。正好近期用到了。

于是在最新的ChatGPT上詢問了一番。。兩次詢問,得到的最優推薦依然是:Android-Image-Cropper。經過一番研究使用。。确實簡單好用。直接看代碼:

首先,你需要引入依賴:

dependencies {
    api 'com.theartofdev.edmodo:android-image-cropper:2.8.+'
}
           

其次,你需要添加手機記憶體通路權限以用來通路相冊

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
           

再然後,是使用,使用的話分為Activity和View兩種弄方式。換言之,就是可以直接內建或者定制使用。當然,每一個都很簡單。

1、直接使用 ( 直接跳轉至内置Activity)

//	啟動取景器擷取用于裁剪的圖像,然後在裁剪Activity中使用該圖像
CropImage.activity()
  .setGuidelines(CropImageView.Guidelines.ON)
  .start(this);

//選擇手機相冊圖檔以裁剪
CropImage.activity(imageUri)
 .start(this);

//	for Fragment(請勿是使用getActivity() )
CropImage.activity()
  .start(getContext(), this);
           

還需要在啟動的Activity中複寫onActivityResult以獲得裁剪結果

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
    CropImage.ActivityResult result = CropImage.getActivityResult(data);
    if (resultCode == RESULT_OK) {
      Uri resultUri = result.getUri();
    } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
      Exception error = result.getError();
    }
  }
}
           

當然,如果你要使用這個Activity,就要為他注冊。

<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
  android:theme="@style/Base.Theme.AppCompat"/> 

<!-- optional (needed if default theme has no action bar) -->
           

2、如果你要定制頁面

首先要在xml中引入

<com.theartofdev.edmodo.cropper.CropImageView
  xmlns:custom="http://schemas.android.com/apk/res-auto"
  android:id="@+id/cropImageView"
  android:layout_width="match_parent"
  android:layout_height="0dp"
  android:layout_weight="1"/>
           

然後Activity中的使用如下:

//把選擇的圖檔傳至view

cropImageView.setImageUriAsync(uri);
// 為了性能和更好的使用者體驗,更傾向于使用uri
cropImageView.setImageBitmap(bitmap);
           

擷取裁剪後的圖像

// subscribe to async event using cropImageView.setOnCropImageCompleteListener(listener)

cropImageView.getCroppedImageAsync();
// or
Bitmap cropped = cropImageView.getCroppedImage();
           

如果需要旋轉圖檔

//xx為每次順時針旋轉度數
.rotateImage(xx)
           

最後,如果你的代碼需要混淆:

将此行添加到你的 Proguard 配置檔案中

-keep class androidx.appcompat.widget.** { *; }
           

最後的最後,如果你需要獲得最新的依賴版本或者更多的功能支援。請查閱 GitHub

END