安卓图片裁剪之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

猜你喜欢

转载自blog.csdn.net/lixinxiaos/article/details/129038219