Skip to content

Using built in CropImageActivity

Arthur edited this page Sep 1, 2017 · 8 revisions
  1. Include the library
compile 'com.theartofdev.edmodo:android-image-cropper:2.5.+'
  1. Add CropImageActivity into your AndroidManifest.xml
<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
 android:theme="@style/Base.Theme.AppCompat"/> <!-- optional (needed if default theme has no action bar) -->
  1. Start CropImageActivity using builder pattern from your activity
// start picker to get image for cropping and then use the image in cropping activity
CropImage.activity()
  .setGuidelines(CropImageView.Guidelines.ON)
  .start(this);

// start cropping activity for pre-acquired image saved on the device
CropImage.activity(imageUri)
 .start(this);

// for fragment (DO NOT use `getActivity()`)
CropImage.activity()
  .start(getContext(), this);
  1. Override onActivityResult method in your activity to get crop result
@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();
        }
    }
}

Custom request code

If you need to customize request code for the activity you can get the intent from the builder and start the activity manually.

Intent intent = CropImage.activity(imageUri)
  .getIntent(getContext());
startActivityForResult(intent, myRequestCode);

Fragment

You can start the CropImageActivity from the fragment and receive the result in the fragment onActivityResult method.
Using AppCompat fragment is the best option that allows you to use direct start method:

CropImage.activity(imageUri)
  .start(getContext(), this); // (DO NOT use `getActivity()`)

otherwise you can get the intent and start the activity manually:

Intent intent = CropImage.activity(imageUri)
  .getIntent(getContext());
startActivityForResult(intent, CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE);

Note: If you override the onActivityResult of the activity then you must call super.onActivityResult(requestCode, resultCode, data); as the first line, otherwise the fragment will not receive the result.

Theme

The activity class is derived from AppCompatActivity so the theme used by it must derive from AppCompat theme.
If your main theme has NoActionBar then you need to specify on the activity to use theme with action bar.

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