diff --git a/cropper/build.gradle b/cropper/build.gradle
index 7bea026c..8994e196 100644
--- a/cropper/build.gradle
+++ b/cropper/build.gradle
@@ -43,6 +43,7 @@ apply from: 'https://raw.githubusercontent.com/blundell/release-android-library/
dependencies {
api "androidx.appcompat:appcompat:$androidXLibraryVersion"
+ api "com.android.support:design:$buildToolsVersion"
implementation "androidx.exifinterface:exifinterface:$androidXLibraryVersion"
}
diff --git a/cropper/src/main/java/com/theartofdev/edmodo/cropper/CropImages.java b/cropper/src/main/java/com/theartofdev/edmodo/cropper/CropImages.java
new file mode 100644
index 00000000..c3504426
--- /dev/null
+++ b/cropper/src/main/java/com/theartofdev/edmodo/cropper/CropImages.java
@@ -0,0 +1,1039 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+package com.theartofdev.edmodo.cropper;
+
+import android.Manifest;
+import android.app.Activity;
+import android.content.ComponentName;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.PorterDuff;
+import android.graphics.PorterDuffXfermode;
+import android.graphics.Rect;
+import android.graphics.RectF;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.provider.MediaStore;
+
+import androidx.annotation.DrawableRes;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.annotation.RequiresApi;
+import androidx.fragment.app.Fragment;
+
+import java.io.File;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Helper to simplify crop image work like starting pick-image acitvity and handling camera/gallery
+ * intents.
+ * The goal of the helper is to simplify the starting and most-common usage of image cropping and
+ * not all porpose all possible scenario one-to-rule-them-all code base. So feel free to use it as
+ * is and as a wiki to make your own.
+ * Added value you get out-of-the-box is some edge case handling that you may miss otherwise, like
+ * the stupid-ass Android camera result URI that may differ from version to version and from device
+ * to device.
+ */
+@SuppressWarnings("WeakerAccess, unused")
+public final class CropImages {
+
+ // region: Fields and Consts
+
+ /** The key used to pass crop image source URI to {@link CropImagesActivity}. */
+ public static final String CROP_IMAGE_EXTRA_SOURCE = "CROP_IMAGE_EXTRA_SOURCE";
+
+ /** The key used to pass crop image options to {@link CropImagesActivity}. */
+ public static final String CROP_IMAGE_EXTRA_OPTIONS = "CROP_IMAGE_EXTRA_OPTIONS";
+
+ /** The key used to pass crop image bundle data to {@link CropImagesActivity}. */
+ public static final String CROP_IMAGE_EXTRA_BUNDLE = "CROP_IMAGE_EXTRA_BUNDLE";
+
+ /** The key used to pass crop image result data back from {@link CropImagesActivity}. */
+ public static final String CROP_IMAGE_EXTRA_RESULT = "CROP_IMAGE_EXTRA_RESULT";
+
+ /**
+ * The request code used to start pick image activity to be used on result to identify the this
+ * specific request.
+ */
+ public static final int PICK_IMAGE_CHOOSER_REQUEST_CODE = 200;
+
+ /** The request code used to request permission to pick image from external storage. */
+ public static final int PICK_IMAGE_PERMISSIONS_REQUEST_CODE = 201;
+
+ /** The request code used to request permission to capture image from camera. */
+ public static final int CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE = 2011;
+
+ /**
+ * The request code used to start {@link CropImagesActivity} to be used on result to identify the
+ * this specific request.
+ */
+ public static final int CROP_IMAGE_ACTIVITY_REQUEST_CODE = 203;
+
+ /** The result code used to return error from {@link CropImagesActivity}. */
+ public static final int CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE = 204;
+ // endregion
+
+ private CropImages() {}
+
+ /**
+ * Create a new bitmap that has all pixels beyond the oval shape transparent. Old bitmap is
+ * recycled.
+ */
+ public static Bitmap toOvalBitmap(@NonNull Bitmap bitmap) {
+ int width = bitmap.getWidth();
+ int height = bitmap.getHeight();
+ Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
+
+ Canvas canvas = new Canvas(output);
+
+ int color = 0xff424242;
+ Paint paint = new Paint();
+
+ paint.setAntiAlias(true);
+ canvas.drawARGB(0, 0, 0, 0);
+ paint.setColor(color);
+
+ RectF rect = new RectF(0, 0, width, height);
+ canvas.drawOval(rect, paint);
+ paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
+ canvas.drawBitmap(bitmap, 0, 0, paint);
+
+ bitmap.recycle();
+
+ return output;
+ }
+
+ /**
+ * Start an activity to get image for cropping using chooser intent that will have all the
+ * available applications for the device like camera (MyCamera), galery (Photos), store apps
+ * (Dropbox), etc.
+ * Use "pick_image_intent_chooser_title" string resource to override pick chooser title.
+ *
+ * @param activity the activity to be used to start activity from
+ */
+ public static void startPickImageActivity(@NonNull Activity activity) {
+ activity.startActivityForResult(
+ getPickImageChooserIntent(activity), PICK_IMAGE_CHOOSER_REQUEST_CODE);
+ }
+
+ /**
+ * Same as {@link #startPickImageActivity(Activity) startPickImageActivity} method but instead of
+ * being called and returning to an Activity, this method can be called and return to a Fragment.
+ *
+ * @param context The Fragments context. Use getContext()
+ * @param fragment The calling Fragment to start and return the image to
+ */
+ public static void startPickImageActivity(@NonNull Context context, @NonNull Fragment fragment) {
+ fragment.startActivityForResult(
+ getPickImageChooserIntent(context), PICK_IMAGE_CHOOSER_REQUEST_CODE);
+ }
+
+ /**
+ * Create a chooser intent to select the source to get image from.
+ * The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).
+ * All possible sources are added to the intent chooser.
+ * Use "pick_image_intent_chooser_title" string resource to override chooser title.
+ *
+ * @param context used to access Android APIs, like content resolve, it is your
+ * activity/fragment/widget.
+ */
+ public static Intent getPickImageChooserIntent(@NonNull Context context) {
+ return getPickImageChooserIntent(
+ context, context.getString(R.string.pick_image_intent_chooser_title), true);
+ }
+
+ /**
+ * Create a chooser intent to select the source to get image from.
+ * The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).
+ * All possible sources are added to the intent chooser.
+ *
+ * @param context used to access Android APIs, like content resolve, it is your
+ * activity/fragment/widget.
+ * @param title the title to use for the chooser UI
+ * @param includeCamera if to include camera intents
+ */
+ public static Intent getPickImageChooserIntent(@NonNull Context context, CharSequence title, boolean includeCamera)
+ {
+ List allIntents = new ArrayList<>();
+ PackageManager packageManager = context.getPackageManager();
+
+ // collect all camera intents if Camera permission is available
+ if (!isExplicitCameraPermissionRequired(context) && includeCamera) {
+ allIntents.addAll(getCameraIntents(context, packageManager));
+ }
+
+ List galleryIntents = getGalleryIntents(packageManager, Intent.ACTION_GET_CONTENT);
+
+ if (galleryIntents.size() == 0) {
+ // if no intents found for get-content try pick intent action (Huawei P9).
+ galleryIntents = getGalleryIntents(packageManager, Intent.ACTION_PICK);
+ }
+ allIntents.addAll(galleryIntents);
+
+ Intent target;
+ if (allIntents.isEmpty())
+ {
+ target = new Intent();
+ }
+ else
+ {
+ target = allIntents.get(allIntents.size() - 1);
+ allIntents.remove(allIntents.size() - 1);
+ }
+
+ // Create a chooser from the main intent
+ Intent chooserIntent = Intent.createChooser(target, title);
+
+ // Add all other intents
+ chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
+
+ return chooserIntent;
+ }
+
+ /**
+ * Get the main Camera intent for capturing image using device camera app. If the outputFileUri is
+ * null, a default Uri will be created with {@link #getCaptureImageOutputUri(Context)}, so then
+ * you will be able to get the pictureUri using {@link #getPickImageResultUri(Context, Intent)}.
+ * Otherwise, it is just you use the Uri passed to this method.
+ *
+ * @param context used to access Android APIs, like content resolve, it is your
+ * activity/fragment/widget.
+ * @param outputFileUri the Uri where the picture will be placed.
+ */
+ public static Intent getCameraIntent(@NonNull Context context, Uri outputFileUri) {
+ Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
+ if (outputFileUri == null) {
+ outputFileUri = getCaptureImageOutputUri(context);
+ }
+ intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
+ return intent;
+ }
+
+ /** Get all Camera intents for capturing image using device camera apps. */
+ public static List getCameraIntents(
+ @NonNull Context context, @NonNull PackageManager packageManager) {
+
+ List allIntents = new ArrayList<>();
+
+ // Determine Uri of camera image to save.
+ Uri outputFileUri = getCaptureImageOutputUri(context);
+
+ Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
+ List listCam = packageManager.queryIntentActivities(captureIntent, 0);
+ for (ResolveInfo res : listCam) {
+ Intent intent = new Intent(captureIntent);
+ intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
+ intent.setPackage(res.activityInfo.packageName);
+ if (outputFileUri != null) {
+ intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
+ }
+ allIntents.add(intent);
+ }
+
+ return allIntents;
+ }
+
+ /**
+ * Get all Gallery intents for getting image from one of the apps of the device that handle
+ * images.
+ */
+ public static List getGalleryIntents(@NonNull PackageManager packageManager, String action)
+ {
+ List intents = new ArrayList<>();
+ Intent galleryIntent = Intent.ACTION_GET_CONTENT.equals(action) ? new Intent(action).setType("image/*") : new Intent(action).setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
+ galleryIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
+
+ List listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
+ for (ResolveInfo res : listGallery)
+ {
+ Intent intent = new Intent(galleryIntent);
+ intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
+ intent.setPackage(res.activityInfo.packageName);
+ intents.add(intent);
+ }
+
+ try {
+ for (Intent intent : intents) {
+ if (intent
+ .getComponent()
+ .getClassName()
+ .equals("com.android.documentsui.DocumentsActivity")) {
+ intents.remove(intent);
+ break;
+ }
+ }
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return intents;
+ }
+
+ /**
+ * Check if explicetly requesting camera permission is required.
+ * It is required in Android Marshmellow and above if "CAMERA" permission is requested in the
+ * manifest.
+ * See StackOverflow
+ * question.
+ */
+ public static boolean isExplicitCameraPermissionRequired(@NonNull Context context) {
+ return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
+ && hasPermissionInManifest(context, "android.permission.CAMERA")
+ && context.checkSelfPermission(Manifest.permission.CAMERA)
+ != PackageManager.PERMISSION_GRANTED;
+ }
+
+ /**
+ * Check if the app requests a specific permission in the manifest.
+ *
+ * @param permissionName the permission to check
+ * @return true - the permission in requested in manifest, false - not.
+ */
+ public static boolean hasPermissionInManifest(
+ @NonNull Context context, @NonNull String permissionName) {
+ String packageName = context.getPackageName();
+ try {
+ PackageInfo packageInfo =
+ context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
+ final String[] declaredPermisisons = packageInfo.requestedPermissions;
+ if (declaredPermisisons != null && declaredPermisisons.length > 0) {
+ for (String p : declaredPermisisons) {
+ if (p.equalsIgnoreCase(permissionName)) {
+ return true;
+ }
+ }
+ }
+ } catch (PackageManager.NameNotFoundException e) {
+ }
+ return false;
+ }
+
+ /**
+ * Get URI to image received from capture by camera.
+ *
+ * @param context used to access Android APIs, like content resolve, it is your
+ * activity/fragment/widget.
+ */
+ public static Uri getCaptureImageOutputUri(@NonNull Context context)
+ {
+ Uri outputFileUri = null;
+ File getImage = context.getExternalCacheDir();
+ if (getImage != null) {
+ outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
+ }
+ return outputFileUri;
+ }
+
+ /**
+ * Get the URI of the selected image from {@link #getPickImageChooserIntent(Context)}.
+ * Will return the correct URI for camera and gallery image.
+ *
+ * @param context used to access Android APIs, like content resolve, it is your
+ * activity/fragment/widget.
+ * @param data the returned data of the activity result
+ */
+ public static Uri getPickImageResultUri(@NonNull Context context, @Nullable Intent data)
+ {
+ boolean isCamera = true;
+
+ if (data != null && data.getData() != null)
+ {
+ String action = data.getAction();
+ isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
+ }
+
+ return isCamera || data.getData() == null ? getCaptureImageOutputUri(context) : data.getData();
+ }
+
+ /**
+ * Check if the given picked image URI requires READ_EXTERNAL_STORAGE permissions.
+ * Only relevant for API version 23 and above and not required for all URI's depends on the
+ * implementation of the app that was used for picking the image. So we just test if we can open
+ * the stream or do we get an exception when we try, Android is awesome.
+ *
+ * @param context used to access Android APIs, like content resolve, it is your
+ * activity/fragment/widget.
+ * @param uri the result URI of image pick.
+ * @return true - required permission are not granted, false - either no need for permissions or
+ * they are granted
+ */
+ public static boolean isReadExternalStoragePermissionsRequired(@NonNull Context context, @NonNull ArrayList uri)
+ {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
+ {
+
+ for (int i = 0; i < uri.size(); i++)
+ {
+ if(isUriRequiresPermissions(context, uri.get(i)))
+ return true;
+ }
+
+ return false;
+ }
+ else
+ return false;
+ }
+
+ /**
+ * Check if the given picked image URI requires READ_EXTERNAL_STORAGE permissions.
+ * Only relevant for API version 23 and above and not required for all URI's depends on the
+ * implementation of the app that was used for picking the image. So we just test if we can open
+ * the stream or do we get an exception when we try, Android is awesome.
+ *
+ * @param context used to access Android APIs, like content resolve, it is your
+ * activity/fragment/widget.
+ * @param uri the result URI of image pick.
+ * @return true - required permission are not granted, false - either no need for permissions or
+ * they are granted
+ */
+ public static boolean isReadExternalStoragePermissionsRequired(@NonNull Context context, @NonNull Uri uri)
+ {
+ return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
+ && context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && isUriRequiresPermissions(context, uri);
+ }
+
+ /**
+ * Test if we can open the given Android URI to test if permission required error is thrown.
+ * Only relevant for API version 23 and above.
+ *
+ * @param context used to access Android APIs, like content resolve, it is your
+ * activity/fragment/widget.
+ * @param uri the result URI of image pick.
+ */
+ public static boolean isUriRequiresPermissions(@NonNull Context context, @NonNull Uri uri)
+ {
+ try
+ {
+ ContentResolver resolver = context.getContentResolver();
+ InputStream stream = resolver.openInputStream(uri);
+ if (stream != null) {
+ stream.close();
+ }
+ return false;
+ } catch (Exception e) {
+ return true;
+ }
+ }
+
+ /**
+ * Create {@link ActivityBuilder} instance to open image picker for cropping and then start {@link
+ * CropImagesActivity} to crop the selected image.
+ * Result will be received in {@link Activity#onActivityResult(int, int, Intent)} and can be
+ * retrieved using {@link #getActivityResult(Intent)}.
+ *
+ * @return builder for Crop Image Activity
+ */
+ public static ActivityBuilder activity() {
+ return new ActivityBuilder(null);
+ }
+
+ /**
+ * Create {@link ActivityBuilder} instance to start {@link CropImagesActivity} to crop the given
+ * image.
+ * Result will be received in {@link Activity#onActivityResult(int, int, Intent)} and can be
+ * retrieved using {@link #getActivityResult(Intent)}.
+ *
+ * @param uri the image Android uri source to crop or null to start a picker
+ * @return builder for Crop Image Activity
+ */
+ public static ActivityBuilder activity(@Nullable ArrayList uri) {
+ return new ActivityBuilder(uri);
+ }
+
+ /**
+ * Get {@link CropImagesActivity} result data object for crop image activity started using {@link
+ * #activity(Uri)}.
+ *
+ * @param data result data intent as received in {@link Activity#onActivityResult(int, int,
+ * Intent)}.
+ * @return Crop Image Activity Result object or null if none exists
+ */
+ public static ActivityResult getActivityResult(@Nullable Intent data) {
+ return data != null ? (ActivityResult) data.getParcelableExtra(CROP_IMAGE_EXTRA_RESULT) : null;
+ }
+
+ // region: Inner class: ActivityBuilder
+
+ /** Builder used for creating Image Crop Activity by user request. */
+ public static final class ActivityBuilder {
+
+ /** The image to crop source Android uri. */
+ @Nullable private final ArrayList mSource;
+
+ /** Options for image crop UX */
+ private final CropImageOptions mOptions;
+
+ private ActivityBuilder(@Nullable ArrayList source) {
+ mSource = source;
+ mOptions = new CropImageOptions();
+ }
+
+ /** Get {@link CropImagesActivity} intent to start the activity. */
+ public Intent getIntent(@NonNull Context context) {
+ return getIntent(context, CropImagesActivity.class);
+ }
+
+ /** Get {@link CropImagesActivity} intent to start the activity. */
+ public Intent getIntent(@NonNull Context context, @Nullable Class> cls) {
+ mOptions.validate();
+
+ Intent intent = new Intent();
+ intent.setClass(context, cls);
+ Bundle bundle = new Bundle();
+ bundle.putParcelableArrayList(CROP_IMAGE_EXTRA_SOURCE, mSource);
+ bundle.putParcelable(CROP_IMAGE_EXTRA_OPTIONS, mOptions);
+ intent.putExtra(CropImage.CROP_IMAGE_EXTRA_BUNDLE, bundle);
+ return intent;
+ }
+
+ /**
+ * Start {@link CropImagesActivity}.
+ *
+ * @param activity activity to receive result
+ */
+ public void start(@NonNull Activity activity) {
+ mOptions.validate();
+ activity.startActivityForResult(getIntent(activity), CROP_IMAGE_ACTIVITY_REQUEST_CODE);
+ }
+
+ /**
+ * Start {@link CropImagesActivity}.
+ *
+ * @param activity activity to receive result
+ */
+ public void start(@NonNull Activity activity, @Nullable Class> cls) {
+ mOptions.validate();
+ activity.startActivityForResult(getIntent(activity, cls), CROP_IMAGE_ACTIVITY_REQUEST_CODE);
+ }
+
+ /**
+ * Start {@link CropImagesActivity}.
+ *
+ * @param fragment fragment to receive result
+ */
+ public void start(@NonNull Context context, @NonNull Fragment fragment) {
+ fragment.startActivityForResult(getIntent(context), CROP_IMAGE_ACTIVITY_REQUEST_CODE);
+ }
+
+ /**
+ * Start {@link CropImagesActivity}.
+ *
+ * @param fragment fragment to receive result
+ */
+ @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
+ public void start(@NonNull Context context, @NonNull android.app.Fragment fragment) {
+ fragment.startActivityForResult(getIntent(context), CROP_IMAGE_ACTIVITY_REQUEST_CODE);
+ }
+
+ /**
+ * Start {@link CropImagesActivity}.
+ *
+ * @param fragment fragment to receive result
+ */
+ public void start(
+ @NonNull Context context, @NonNull Fragment fragment, @Nullable Class> cls) {
+ fragment.startActivityForResult(getIntent(context, cls), CROP_IMAGE_ACTIVITY_REQUEST_CODE);
+ }
+
+ /**
+ * Start {@link CropImagesActivity}.
+ *
+ * @param fragment fragment to receive result
+ */
+ @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
+ public void start(
+ @NonNull Context context, @NonNull android.app.Fragment fragment, @Nullable Class> cls) {
+ fragment.startActivityForResult(getIntent(context, cls), CROP_IMAGE_ACTIVITY_REQUEST_CODE);
+ }
+
+ /**
+ * The shape of the cropping window.
+ * To set square/circle crop shape set aspect ratio to 1:1.
+ * Default: RECTANGLE
+ */
+ public ActivityBuilder setCropShape(@NonNull CropImageView.CropShape cropShape) {
+ mOptions.cropShape = cropShape;
+ return this;
+ }
+
+ /**
+ * An edge of the crop window will snap to the corresponding edge of a specified bounding box
+ * when the crop window edge is less than or equal to this distance (in pixels) away from the
+ * bounding box edge (in pixels).
+ * Default: 3dp
+ */
+ public ActivityBuilder setSnapRadius(float snapRadius) {
+ mOptions.snapRadius = snapRadius;
+ return this;
+ }
+
+ /**
+ * The radius of the touchable area around the handle (in pixels).
+ * We are basing this value off of the recommended 48dp Rhythm.
+ * See: http://developer.android.com/design/style/metrics-grids.html#48dp-rhythm
+ * Default: 48dp
+ */
+ public ActivityBuilder setTouchRadius(float touchRadius) {
+ mOptions.touchRadius = touchRadius;
+ return this;
+ }
+
+ /**
+ * whether the guidelines should be on, off, or only showing when resizing.
+ * Default: ON_TOUCH
+ */
+ public ActivityBuilder setGuidelines(@NonNull CropImageView.Guidelines guidelines) {
+ mOptions.guidelines = guidelines;
+ return this;
+ }
+
+ /**
+ * The initial scale type of the image in the crop image view
+ * Default: FIT_CENTER
+ */
+ public ActivityBuilder setScaleType(@NonNull CropImageView.ScaleType scaleType) {
+ mOptions.scaleType = scaleType;
+ return this;
+ }
+
+ /**
+ * if to show crop overlay UI what contains the crop window UI surrounded by background over the
+ * cropping image.
+ * default: true, may disable for animation or frame transition.
+ */
+ public ActivityBuilder setShowCropOverlay(boolean showCropOverlay) {
+ mOptions.showCropOverlay = showCropOverlay;
+ return this;
+ }
+
+ /**
+ * if auto-zoom functionality is enabled.
+ * default: true.
+ */
+ public ActivityBuilder setAutoZoomEnabled(boolean autoZoomEnabled) {
+ mOptions.autoZoomEnabled = autoZoomEnabled;
+ return this;
+ }
+
+ /**
+ * if multi touch functionality is enabled.
+ * default: true.
+ */
+ public ActivityBuilder setMultiTouchEnabled(boolean multiTouchEnabled) {
+ mOptions.multiTouchEnabled = multiTouchEnabled;
+ return this;
+ }
+
+ /**
+ * The max zoom allowed during cropping.
+ * Default: 4
+ */
+ public ActivityBuilder setMaxZoom(int maxZoom) {
+ mOptions.maxZoom = maxZoom;
+ return this;
+ }
+
+ /**
+ * The initial crop window padding from image borders in percentage of the cropping image
+ * dimensions.
+ * Default: 0.1
+ */
+ public ActivityBuilder setInitialCropWindowPaddingRatio(float initialCropWindowPaddingRatio) {
+ mOptions.initialCropWindowPaddingRatio = initialCropWindowPaddingRatio;
+ return this;
+ }
+
+ /**
+ * whether the width to height aspect ratio should be maintained or free to change.
+ * Default: false
+ */
+ public ActivityBuilder setFixAspectRatio(boolean fixAspectRatio) {
+ mOptions.fixAspectRatio = fixAspectRatio;
+ return this;
+ }
+
+ /**
+ * the X,Y value of the aspect ratio.
+ * Also sets fixes aspect ratio to TRUE.
+ * Default: 1/1
+ *
+ * @param aspectRatioX the width
+ * @param aspectRatioY the height
+ */
+ public ActivityBuilder setAspectRatio(int aspectRatioX, int aspectRatioY) {
+ mOptions.aspectRatioX = aspectRatioX;
+ mOptions.aspectRatioY = aspectRatioY;
+ mOptions.fixAspectRatio = true;
+ return this;
+ }
+
+ /**
+ * the thickness of the guidelines lines (in pixels).
+ * Default: 3dp
+ */
+ public ActivityBuilder setBorderLineThickness(float borderLineThickness) {
+ mOptions.borderLineThickness = borderLineThickness;
+ return this;
+ }
+
+ /**
+ * the color of the guidelines lines.
+ * Default: Color.argb(170, 255, 255, 255)
+ */
+ public ActivityBuilder setBorderLineColor(int borderLineColor) {
+ mOptions.borderLineColor = borderLineColor;
+ return this;
+ }
+
+ /**
+ * thickness of the corner line (in pixels).
+ * Default: 2dp
+ */
+ public ActivityBuilder setBorderCornerThickness(float borderCornerThickness) {
+ mOptions.borderCornerThickness = borderCornerThickness;
+ return this;
+ }
+
+ /**
+ * the offset of corner line from crop window border (in pixels).
+ * Default: 5dp
+ */
+ public ActivityBuilder setBorderCornerOffset(float borderCornerOffset) {
+ mOptions.borderCornerOffset = borderCornerOffset;
+ return this;
+ }
+
+ /**
+ * the length of the corner line away from the corner (in pixels).
+ * Default: 14dp
+ */
+ public ActivityBuilder setBorderCornerLength(float borderCornerLength) {
+ mOptions.borderCornerLength = borderCornerLength;
+ return this;
+ }
+
+ /**
+ * the color of the corner line.
+ * Default: WHITE
+ */
+ public ActivityBuilder setBorderCornerColor(int borderCornerColor) {
+ mOptions.borderCornerColor = borderCornerColor;
+ return this;
+ }
+
+ /**
+ * the thickness of the guidelines lines (in pixels).
+ * Default: 1dp
+ */
+ public ActivityBuilder setGuidelinesThickness(float guidelinesThickness) {
+ mOptions.guidelinesThickness = guidelinesThickness;
+ return this;
+ }
+
+ /**
+ * the color of the guidelines lines.
+ * Default: Color.argb(170, 255, 255, 255)
+ */
+ public ActivityBuilder setGuidelinesColor(int guidelinesColor) {
+ mOptions.guidelinesColor = guidelinesColor;
+ return this;
+ }
+
+ /**
+ * the color of the overlay background around the crop window cover the image parts not in the
+ * crop window.
+ * Default: Color.argb(119, 0, 0, 0)
+ */
+ public ActivityBuilder setBackgroundColor(int backgroundColor) {
+ mOptions.backgroundColor = backgroundColor;
+ return this;
+ }
+
+ /**
+ * the min size the crop window is allowed to be (in pixels).
+ * Default: 42dp, 42dp
+ */
+ public ActivityBuilder setMinCropWindowSize(int minCropWindowWidth, int minCropWindowHeight) {
+ mOptions.minCropWindowWidth = minCropWindowWidth;
+ mOptions.minCropWindowHeight = minCropWindowHeight;
+ return this;
+ }
+
+ /**
+ * the min size the resulting cropping image is allowed to be, affects the cropping window
+ * limits (in pixels).
+ * Default: 40px, 40px
+ */
+ public ActivityBuilder setMinCropResultSize(int minCropResultWidth, int minCropResultHeight) {
+ mOptions.minCropResultWidth = minCropResultWidth;
+ mOptions.minCropResultHeight = minCropResultHeight;
+ return this;
+ }
+
+ /**
+ * the max size the resulting cropping image is allowed to be, affects the cropping window
+ * limits (in pixels).
+ * Default: 99999, 99999
+ */
+ public ActivityBuilder setMaxCropResultSize(int maxCropResultWidth, int maxCropResultHeight) {
+ mOptions.maxCropResultWidth = maxCropResultWidth;
+ mOptions.maxCropResultHeight = maxCropResultHeight;
+ return this;
+ }
+
+ /**
+ * the title of the {@link CropImagesActivity}.
+ * Default: ""
+ */
+ public ActivityBuilder setActivityTitle(CharSequence activityTitle) {
+ mOptions.activityTitle = activityTitle;
+ return this;
+ }
+
+ /**
+ * the color to use for action bar items icons.
+ * Default: NONE
+ */
+ public ActivityBuilder setActivityMenuIconColor(int activityMenuIconColor) {
+ mOptions.activityMenuIconColor = activityMenuIconColor;
+ return this;
+ }
+
+ /**
+ * the Android Uri to save the cropped image to.
+ * Default: NONE, will create a temp file
+ */
+ public ActivityBuilder setOutputUri(Uri outputUri) {
+ mOptions.outputUri = outputUri;
+ return this;
+ }
+
+ /**
+ * the compression format to use when writting the image.
+ * Default: JPEG
+ */
+ public ActivityBuilder setOutputCompressFormat(Bitmap.CompressFormat outputCompressFormat) {
+ mOptions.outputCompressFormat = outputCompressFormat;
+ return this;
+ }
+
+ /**
+ * the quility (if applicable) to use when writting the image (0 - 100).
+ * Default: 90
+ */
+ public ActivityBuilder setOutputCompressQuality(int outputCompressQuality) {
+ mOptions.outputCompressQuality = outputCompressQuality;
+ return this;
+ }
+
+ /**
+ * the size to resize the cropped image to.
+ * Uses {@link CropImageView.RequestSizeOptions#RESIZE_INSIDE} option.
+ * Default: 0, 0 - not set, will not resize
+ */
+ public ActivityBuilder setRequestedSize(int reqWidth, int reqHeight) {
+ return setRequestedSize(reqWidth, reqHeight, CropImageView.RequestSizeOptions.RESIZE_INSIDE);
+ }
+
+ /**
+ * the size to resize the cropped image to.
+ * Default: 0, 0 - not set, will not resize
+ */
+ public ActivityBuilder setRequestedSize(
+ int reqWidth, int reqHeight, CropImageView.RequestSizeOptions options) {
+ mOptions.outputRequestWidth = reqWidth;
+ mOptions.outputRequestHeight = reqHeight;
+ mOptions.outputRequestSizeOptions = options;
+ return this;
+ }
+
+ /**
+ * if the result of crop image activity should not save the cropped image bitmap.
+ * Used if you want to crop the image manually and need only the crop rectangle and rotation
+ * data.
+ * Default: false
+ */
+ public ActivityBuilder setNoOutputImage(boolean noOutputImage) {
+ mOptions.noOutputImage = noOutputImage;
+ return this;
+ }
+
+ /**
+ * the initial rectangle to set on the cropping image after loading.
+ * Default: NONE - will initialize using initial crop window padding ratio
+ */
+ public ActivityBuilder setInitialCropWindowRectangle(Rect initialCropWindowRectangle) {
+ mOptions.initialCropWindowRectangle = initialCropWindowRectangle;
+ return this;
+ }
+
+ /**
+ * the initial rotation to set on the cropping image after loading (0-360 degrees clockwise).
+ *
+ * Default: NONE - will read image exif data
+ */
+ public ActivityBuilder setInitialRotation(int initialRotation) {
+ mOptions.initialRotation = (initialRotation + 360) % 360;
+ return this;
+ }
+
+ /**
+ * if to allow rotation during cropping.
+ * Default: true
+ */
+ public ActivityBuilder setAllowRotation(boolean allowRotation) {
+ mOptions.allowRotation = allowRotation;
+ return this;
+ }
+
+ /**
+ * if to allow flipping during cropping.
+ * Default: true
+ */
+ public ActivityBuilder setAllowFlipping(boolean allowFlipping) {
+ mOptions.allowFlipping = allowFlipping;
+ return this;
+ }
+
+ /**
+ * if to allow counter-clockwise rotation during cropping.
+ * Note: if rotation is disabled this option has no effect.
+ * Default: false
+ */
+ public ActivityBuilder setAllowCounterRotation(boolean allowCounterRotation) {
+ mOptions.allowCounterRotation = allowCounterRotation;
+ return this;
+ }
+
+ /**
+ * The amount of degreees to rotate clockwise or counter-clockwise (0-360).
+ * Default: 90
+ */
+ public ActivityBuilder setRotationDegrees(int rotationDegrees) {
+ mOptions.rotationDegrees = (rotationDegrees + 360) % 360;
+ return this;
+ }
+
+ /**
+ * whether the image should be flipped horizontally.
+ * Default: false
+ */
+ public ActivityBuilder setFlipHorizontally(boolean flipHorizontally) {
+ mOptions.flipHorizontally = flipHorizontally;
+ return this;
+ }
+
+ /**
+ * whether the image should be flipped vertically.
+ * Default: false
+ */
+ public ActivityBuilder setFlipVertically(boolean flipVertically) {
+ mOptions.flipVertically = flipVertically;
+ return this;
+ }
+
+ /**
+ * optional, set crop menu crop button title.
+ * Default: null, will use resource string: crop_image_menu_crop
+ */
+ public ActivityBuilder setCropMenuCropButtonTitle(CharSequence title) {
+ mOptions.cropMenuCropButtonTitle = title;
+ return this;
+ }
+
+ /**
+ * Image resource id to use for crop icon instead of text.
+ * Default: 0
+ */
+ public ActivityBuilder setCropMenuCropButtonIcon(@DrawableRes int drawableResource) {
+ mOptions.cropMenuCropButtonIcon = drawableResource;
+ return this;
+ }
+ }
+
+ /** Result data of Crop Image Activity. */
+ public static final class ActivityResult implements Parcelable
+ {
+ private ArrayList mOriginalUri;
+ private ArrayList mResultUri;
+ private Exception mError;
+
+ public static final Creator CREATOR =
+ new Creator() {
+ @Override
+ public ActivityResult createFromParcel(Parcel in) {
+ return new ActivityResult(in);
+ }
+
+ @Override
+ public ActivityResult[] newArray(int size) {
+ return new ActivityResult[size];
+ }
+ };
+
+ public ActivityResult(ArrayList originalUri, ArrayList resultUri, Exception error)
+ {
+ mOriginalUri = originalUri;
+ mResultUri = resultUri;
+ mError = error;
+ }
+
+ public ArrayList getOriginalUri()
+ {
+ return mOriginalUri;
+ }
+
+ public ArrayList getResultUri()
+ {
+ return mResultUri;
+ }
+
+ public Exception getError()
+ {
+ return mError;
+ }
+
+ protected ActivityResult(Parcel in)
+ {
+ mOriginalUri = in.readArrayList(Uri.class.getClassLoader());
+ mResultUri = in.readArrayList(Uri.class.getClassLoader());
+ mError = (Exception) in.readSerializable();
+ }
+
+ @Override
+ public void writeToParcel(Parcel dest, int flags) {
+ dest.writeList(mOriginalUri);
+ dest.writeList(mResultUri);
+ dest.writeSerializable(mError);
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+ }
+}
diff --git a/cropper/src/main/java/com/theartofdev/edmodo/cropper/CropImagesActivity.java b/cropper/src/main/java/com/theartofdev/edmodo/cropper/CropImagesActivity.java
new file mode 100644
index 00000000..a82349cf
--- /dev/null
+++ b/cropper/src/main/java/com/theartofdev/edmodo/cropper/CropImagesActivity.java
@@ -0,0 +1,471 @@
+// "Therefore those skilled at the unorthodox
+// are infinite as heaven and earth,
+// inexhaustible as the great rivers.
+// When they come to an end,
+// they begin again,
+// like the days and months;
+// they die and are reborn,
+// like the four seasons."
+//
+// - Sun Tsu,
+// "The Art of War"
+
+package com.theartofdev.edmodo.cropper;
+
+import android.Manifest;
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.content.ClipData;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.res.Resources;
+import android.graphics.Bitmap;
+import android.net.Uri;
+import android.os.Bundle;
+import android.provider.MediaStore;
+import android.util.Log;
+import android.util.TypedValue;
+import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ImageView;
+import android.widget.ProgressBar;
+import android.widget.Toast;
+
+import androidx.annotation.NonNull;
+import androidx.appcompat.app.ActionBar;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.viewpager.widget.PagerAdapter;
+import androidx.viewpager.widget.ViewPager;
+
+import com.google.android.material.tabs.TabLayout;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * Built-in activity for image cropping.
+ * Use {@link CropImages#activity(ArrayList < Uri >)} to create a builder to start this activity.
+ */
+public class CropImagesActivity extends AppCompatActivity
+{
+ /** The crop image view library widget used in the activity */
+ private ViewPager imageViewPager;
+ private TabLayout mTabLayout;
+ private ImagePagerAdapter mediaPagerAdapter;
+ private ProgressBar pbView;
+
+ private ArrayList mCropImageUri;
+ private ArrayList mSavedCropImageUri;
+
+ /** the options that were set for the crop image */
+ private CropImageOptions mOptions;
+ int mSelectedPosition = 0;
+ HashMap retainer = new HashMap<>();
+ int deviceWidth = getScreenWidth();
+ int deviceHeight = getScreenHeight();
+ int dp_60 = convertDpToPixels(60);
+ int dp_8 = convertDpToPixels(8);
+
+ @Override
+ @SuppressLint("NewApi")
+ public void onCreate(Bundle savedInstanceState)
+ {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_crop_images);
+
+ pbView = findViewById(R.id.pbView);
+ imageViewPager = findViewById(R.id.imageViewPager);
+ mTabLayout = findViewById(R.id.filter_tabs);
+
+ pbView.setVisibility(View.GONE);
+ Bundle bundle = getIntent().getBundleExtra(CropImages.CROP_IMAGE_EXTRA_BUNDLE);
+ mOptions = bundle.getParcelable(CropImages.CROP_IMAGE_EXTRA_OPTIONS);
+ mCropImageUri = bundle.getParcelableArrayList(CropImages.CROP_IMAGE_EXTRA_SOURCE);
+
+ mSavedCropImageUri = new ArrayList<>();
+ if (mCropImageUri == null)
+ mCropImageUri = new ArrayList<>();
+
+ if (savedInstanceState == null)
+ {
+ if (mCropImageUri.size() == 0)
+ {
+ if (CropImages.isExplicitCameraPermissionRequired(this))
+ requestPermissions(new String[] {Manifest.permission.CAMERA}, CropImages.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE);
+ else
+ CropImages.startPickImageActivity(this);
+ }
+ else if (CropImages.isReadExternalStoragePermissionsRequired(this, mCropImageUri))
+ requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, CropImages.PICK_IMAGE_PERMISSIONS_REQUEST_CODE);
+ else
+ setupViewPager();
+ }
+
+ ActionBar actionBar = getSupportActionBar();
+ if (actionBar != null)
+ {
+ CharSequence title = mOptions != null &&
+ mOptions.activityTitle != null && mOptions.activityTitle.length() > 0
+ ? mOptions.activityTitle
+ : getResources().getString(R.string.crop_image_activity_title);
+ actionBar.setTitle(title);
+ actionBar.setDisplayHomeAsUpEnabled(true);
+ }
+ }
+
+ private void setupViewPager()
+ {
+ for (int x = 0; x < mCropImageUri.size(); x++)
+ mSavedCropImageUri.add((Uri) ParcelableHelper.immediateDeepCopy(mCropImageUri.get(x)));
+
+ mediaPagerAdapter = new ImagePagerAdapter();
+ imageViewPager.setAdapter(mediaPagerAdapter);
+ imageViewPager.setCurrentItem(mSelectedPosition);
+ mTabLayout.setupWithViewPager(imageViewPager);
+
+ if(mCropImageUri.size() == 1)
+ mTabLayout.setVisibility(View.GONE);
+
+ for (int i = 0; i < mTabLayout.getTabCount(); i++)
+ {
+ TabLayout.Tab tab = mTabLayout.getTabAt(i);
+ tab.setCustomView(mediaPagerAdapter.getTabView(i));
+ }
+
+ imageViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
+ {
+ @Override
+ public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
+
+ }
+
+ @Override
+ public void onPageSelected(int position)
+ {
+ Log.d("fatal", "Fragment no. : " + position + " is visible now.");
+ mSelectedPosition = position;
+ }
+
+ @Override
+ public void onPageScrollStateChanged(int state)
+ {
+ }
+ });
+ }
+
+
+ public static int getScreenWidth() {
+ return Resources.getSystem().getDisplayMetrics().widthPixels;
+ }
+
+ public static int getScreenHeight() {
+ return Resources.getSystem().getDisplayMetrics().heightPixels;
+ }
+
+ public int convertDpToPixels(float dp)
+ {
+ try {
+ return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, Resources.getSystem().getDisplayMetrics());
+ } catch (Exception ignored) {
+ }
+
+ return (int) dp;
+ }
+
+ class ImagePagerAdapter extends PagerAdapter
+ {
+ @Override
+ public int getCount()
+ {
+ return (null != mSavedCropImageUri) ? mSavedCropImageUri.size() : 0;
+ }
+
+ @Override
+ public boolean isViewFromObject(View view, Object object)
+ {
+
+ return view == object;
+ }
+
+ @Override
+ public int getItemPosition(@NonNull Object object)
+ {
+
+ return super.getItemPosition(object);
+ }
+
+ @Override
+ public View instantiateItem(ViewGroup container, int position)
+ {
+ TouchImageView imageView = new TouchImageView(container.getContext());
+
+ setImageInTouchView(position, imageView);
+
+ container.addView(imageView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
+ retainer.put(position, imageView);
+
+ Log.d("fatal", "Load image for position" + position);
+ return imageView;
+ }
+
+ @Override
+ public void destroyItem(ViewGroup container, int position, Object object)
+ {
+ retainer.remove(position);
+ container.removeView((View) object);
+ }
+
+ public View getTabView(int position)
+ {
+ View v = LayoutInflater.from(CropImagesActivity.this).inflate(R.layout.crop_media_tab, null);
+ final ImageView tv = v.findViewById(R.id.name);
+
+ tv.setImageResource(R.drawable.placeholder);
+ ImageLoadTask imageLoadTask = new ImageLoadTask(CropImagesActivity.this, mSavedCropImageUri.get(position), dp_60, dp_60, new ImageLoadTaskListener() {
+ @Override
+ public void onComplete(Bitmap bitmap) {
+ Log.d("fatal", "Bitmap width : "+ bitmap.getWidth() + " height : "+ bitmap.getHeight());
+ tv.setImageBitmap(bitmap);
+ }
+
+ @Override
+ public void onError(Throwable error) {
+ Log.d("fatal", "Error : "+ error.getMessage());
+ tv.setImageResource(R.drawable.placeholder);
+ }
+ });
+ mExecutorLoadService.execute(imageLoadTask);
+
+ return v;
+ }
+ }
+
+ public void setImageInTouchView(int position, final ImageView imageView)
+ {
+ int width = deviceWidth - 2*dp_8;
+ int height = deviceHeight - 2*dp_8 - dp_60;
+
+ imageView.setImageResource(R.drawable.placeholder);
+ ImageLoadTask imageLoadTask = new ImageLoadTask(CropImagesActivity.this, mSavedCropImageUri.get(position), width, height, new ImageLoadTaskListener() {
+ @Override
+ public void onComplete(Bitmap bitmap) {
+ Log.d("fatal", "Bitmap width : "+ bitmap.getWidth() + " height : "+ bitmap.getHeight());
+ imageView.setImageBitmap(bitmap);
+ }
+
+ @Override
+ public void onError(Throwable error) {
+ error.printStackTrace();
+ Log.d("fatal", "Error : "+ error.getMessage());
+ imageView.setImageResource(R.drawable.placeholder);
+ }
+ });
+
+ mExecutorLoadService.execute(imageLoadTask);
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu)
+ {
+ getMenuInflater().inflate(R.menu.menu_crop_images, menu);
+
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item)
+ {
+ if (item.getItemId() == R.id.image_menu_done)
+ {
+ startCropping();
+ return true;
+ }
+
+ if (item.getItemId() == R.id.image_menu_crop)
+ {
+ CropImage.activity(mCropImageUri.get(mSelectedPosition))
+ .setGuidelines(mOptions.guidelines)
+ .setAllowRotation(mOptions.allowRotation)
+ .setAllowCounterRotation(mOptions.allowCounterRotation)
+ .setRequestedSize(mOptions.outputRequestWidth, mOptions.outputRequestHeight)
+ .setAllowFlipping(mOptions.allowFlipping)
+ .setAutoZoomEnabled(mOptions.autoZoomEnabled)
+ .setMinCropResultSize(mOptions.minCropResultWidth, mOptions.minCropResultHeight)
+ .setMinCropWindowSize(mOptions.minCropWindowWidth, mOptions.minCropWindowHeight)
+ .setActivityMenuIconColor(mOptions.activityMenuIconColor)
+ .start(this);
+
+ return true;
+ }
+
+ if (item.getItemId() == android.R.id.home) {
+ setResultCancel();
+ return true;
+ }
+
+ return super.onOptionsItemSelected(item);
+ }
+
+ private ExecutorService mExecutorService = Executors.newFixedThreadPool(1);
+ private ImageCompressTask imageCompressTask;
+
+ private ExecutorService mExecutorLoadService = Executors.newFixedThreadPool(1);
+
+ private void startCropping()
+ {
+ pbView.setVisibility(View.VISIBLE);
+ imageCompressTask = new ImageCompressTask(CropImagesActivity.this, mSavedCropImageUri, mOptions, iImageCompressTaskListener);
+ mExecutorService.execute(imageCompressTask);
+ }
+
+ //image compress task callback
+ private IImageCompressTaskListener iImageCompressTaskListener = new IImageCompressTaskListener()
+ {
+ @Override
+ public void onComplete(ArrayList compressed)
+ {
+ Log.d("fatal", "New photo size ==> " + compressed.toString()); //log new file size.
+ pbView.setVisibility(View.GONE);
+ setResult(compressed, null);
+ }
+
+ @Override
+ public void onError(Throwable error)
+ {
+ error.printStackTrace();
+ Log.d("fatal", "Error occurred" );
+ pbView.setVisibility(View.GONE);
+ setResult(null, new Exception(error));
+ }
+ };
+
+ @Override
+ protected void onDestroy()
+ {
+ super.onDestroy();
+
+ //clean up!
+ mExecutorService.shutdown();
+ mExecutorService = null;
+ imageCompressTask = null;
+ }
+
+ @Override
+ public void onBackPressed()
+ {
+ super.onBackPressed();
+ setResultCancel();
+ }
+
+ @Override
+ @SuppressLint("NewApi")
+ protected void onActivityResult(int requestCode, int resultCode, Intent data)
+ {
+ // handle result of pick image chooser
+ if (requestCode == CropImages.PICK_IMAGE_CHOOSER_REQUEST_CODE)
+ {
+ if (resultCode == Activity.RESULT_CANCELED) {
+ // User cancelled the picker. We don't have anything to crop
+ setResultCancel();
+ }
+
+ if (resultCode == Activity.RESULT_OK)
+ {
+ if(data != null)
+ {
+ ClipData clipData = data.getClipData();
+
+ if(clipData == null && data.getData() == null)
+ {
+ String action = data.getAction();
+ boolean isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
+
+ if(isCamera)
+ mCropImageUri.add(CropImages.getCaptureImageOutputUri(this));
+ else
+ setResultCancel();
+ }
+ else if(clipData == null)
+ mCropImageUri.add(data.getData());
+ else
+ {
+ for(int i=0; i= 23 we need to check specifically that we have permissions to read external storage.
+ if (CropImages.isReadExternalStoragePermissionsRequired(this, mCropImageUri))
+ requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, CropImages.PICK_IMAGE_PERMISSIONS_REQUEST_CODE);
+ else
+ setupViewPager();
+ }
+ }
+ else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
+ {
+ CropImage.ActivityResult result = CropImage.getActivityResult(data);
+ if (resultCode == RESULT_OK)
+ {
+ mSavedCropImageUri.set(mSelectedPosition, result.getUri());
+ setImageInTouchView(mSelectedPosition, retainer.get(mSelectedPosition));
+ }
+ }
+ }
+
+ @Override
+ public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults)
+ {
+ if (requestCode == CropImages.PICK_IMAGE_PERMISSIONS_REQUEST_CODE)
+ {
+ if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
+ setupViewPager();
+ else
+ {
+ Toast.makeText(this, R.string.crop_image_activity_no_permissions, Toast.LENGTH_LONG).show();
+ setResultCancel();
+ }
+ }
+
+ if (requestCode == CropImages.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE)
+ {
+ // Irrespective of whether camera permission was given or not, we show the picker
+ // The picker will not add the camera intent if permission is not available
+ CropImages.startPickImageActivity(this);
+ }
+ }
+
+ /** Result with cropped image data or error if failed. */
+ protected void setResult(ArrayList uri, Exception error)
+ {
+ int resultCode = error == null ? RESULT_OK : CropImages.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE;
+ setResult(resultCode, getResultIntent(uri, error));
+ finish();
+ }
+
+ /** Cancel of cropping activity. */
+ protected void setResultCancel() {
+ setResult(RESULT_CANCELED);
+ finish();
+ }
+
+ /** Get intent instance to be used for the result of this activity. */
+ protected Intent getResultIntent(ArrayList resultUri, Exception error)
+ {
+ CropImages.ActivityResult result = new CropImages.ActivityResult(mSavedCropImageUri, resultUri, error);
+
+ Intent intent = new Intent();
+ intent.putExtras(getIntent());
+ intent.putExtra(CropImages.CROP_IMAGE_EXTRA_RESULT, result);
+ return intent;
+ }
+}
\ No newline at end of file
diff --git a/cropper/src/main/java/com/theartofdev/edmodo/cropper/IImageCompressTaskListener.java b/cropper/src/main/java/com/theartofdev/edmodo/cropper/IImageCompressTaskListener.java
new file mode 100644
index 00000000..f9f74931
--- /dev/null
+++ b/cropper/src/main/java/com/theartofdev/edmodo/cropper/IImageCompressTaskListener.java
@@ -0,0 +1,15 @@
+package com.theartofdev.edmodo.cropper;
+
+import android.net.Uri;
+
+import java.util.ArrayList;
+
+/**
+ * Created by root on 9/14/17.
+ */
+
+public interface IImageCompressTaskListener {
+
+ public void onComplete(ArrayList compressed);
+ public void onError(Throwable error);
+}
\ No newline at end of file
diff --git a/cropper/src/main/java/com/theartofdev/edmodo/cropper/ImageCompressTask.java b/cropper/src/main/java/com/theartofdev/edmodo/cropper/ImageCompressTask.java
new file mode 100644
index 00000000..e74343c3
--- /dev/null
+++ b/cropper/src/main/java/com/theartofdev/edmodo/cropper/ImageCompressTask.java
@@ -0,0 +1,71 @@
+package com.theartofdev.edmodo.cropper;
+
+import android.content.Context;
+import android.net.Uri;
+import android.os.Handler;
+import android.os.Looper;
+
+import java.io.IOException;
+import java.util.ArrayList;
+
+public class ImageCompressTask implements Runnable
+{
+ private Context mContext;
+ private ArrayList originalPaths = new ArrayList<>();
+ private Handler mHandler = new Handler(Looper.getMainLooper());
+ private ArrayList result = new ArrayList<>();
+ private IImageCompressTaskListener mIImageCompressTaskListener;
+ private CropImageOptions mOptions;
+
+ public ImageCompressTask(Context context, Uri path, CropImageOptions options, IImageCompressTaskListener compressTaskListener)
+ {
+ originalPaths.add(path);
+ mContext = context;
+ mOptions = options;
+ mIImageCompressTaskListener = compressTaskListener;
+ }
+
+ public ImageCompressTask(Context context, ArrayList paths, CropImageOptions options, IImageCompressTaskListener compressTaskListener)
+ {
+ originalPaths.addAll(paths);
+ mContext = context;
+ mOptions = options;
+ mIImageCompressTaskListener = compressTaskListener;
+ }
+
+ @Override
+ public void run()
+ {
+ try
+ {
+ //Loop through all the given paths and collect the compressed file from Util.getCompressed(Context, String)
+ for (Uri path : originalPaths)
+ {
+ Uri output = Util.getCompressed(mContext, path, mOptions);
+ result.add(output);
+ }
+ //use Handler to post the result back to the main Thread
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+
+ if(mIImageCompressTaskListener != null)
+ mIImageCompressTaskListener.onComplete(result);
+ }
+ });
+ }
+ catch (final IOException ex)
+ {
+ //There was an error, report the error back through the callback
+ mHandler.post(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ if(mIImageCompressTaskListener != null)
+ mIImageCompressTaskListener.onError(ex);
+ }
+ });
+ }
+ }
+}
diff --git a/cropper/src/main/java/com/theartofdev/edmodo/cropper/ImageLoadTask.java b/cropper/src/main/java/com/theartofdev/edmodo/cropper/ImageLoadTask.java
new file mode 100644
index 00000000..1181ce6a
--- /dev/null
+++ b/cropper/src/main/java/com/theartofdev/edmodo/cropper/ImageLoadTask.java
@@ -0,0 +1,46 @@
+package com.theartofdev.edmodo.cropper;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.net.Uri;
+import android.os.Handler;
+import android.os.Looper;
+
+public class ImageLoadTask implements Runnable
+{
+ private Context mContext;
+ private Uri originalPath = null;
+ private Handler mHandler = new Handler(Looper.getMainLooper());
+ private int mReqWidth, mReqHeight;
+ private ImageLoadTaskListener mImageLoadTaskListener;
+
+ public ImageLoadTask(Context context, Uri path, int reqWidth, int reqHeight, ImageLoadTaskListener loadTaskListener)
+ {
+ mContext = context;
+ originalPath = path;
+ mReqWidth = reqWidth;
+ mReqHeight = reqHeight;
+ mImageLoadTaskListener = loadTaskListener;
+ }
+
+ @Override
+ public void run()
+ {
+ final Bitmap output = Util.decodeSampledBitmapFromResource(mContext, originalPath, mReqWidth, mReqHeight);
+
+ //use Handler to post the result back to the main Thread
+ mHandler.post(new Runnable() {
+ @Override
+ public void run()
+ {
+ if(mImageLoadTaskListener != null)
+ {
+ if(output != null)
+ mImageLoadTaskListener.onComplete(output);
+ else
+ mImageLoadTaskListener.onError(new Exception("Bitmap is null"));
+ }
+ }
+ });
+ }
+}
diff --git a/cropper/src/main/java/com/theartofdev/edmodo/cropper/ImageLoadTaskListener.java b/cropper/src/main/java/com/theartofdev/edmodo/cropper/ImageLoadTaskListener.java
new file mode 100644
index 00000000..1ac7be07
--- /dev/null
+++ b/cropper/src/main/java/com/theartofdev/edmodo/cropper/ImageLoadTaskListener.java
@@ -0,0 +1,13 @@
+package com.theartofdev.edmodo.cropper;
+
+import android.graphics.Bitmap;
+
+/**
+ * Created by root on 9/14/17.
+ */
+
+public interface ImageLoadTaskListener {
+
+ public void onComplete(Bitmap bitmap);
+ public void onError(Throwable error);
+}
\ No newline at end of file
diff --git a/cropper/src/main/java/com/theartofdev/edmodo/cropper/ParcelableHelper.java b/cropper/src/main/java/com/theartofdev/edmodo/cropper/ParcelableHelper.java
new file mode 100644
index 00000000..7d2b3733
--- /dev/null
+++ b/cropper/src/main/java/com/theartofdev/edmodo/cropper/ParcelableHelper.java
@@ -0,0 +1,39 @@
+package com.theartofdev.edmodo.cropper;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+public class ParcelableHelper
+{
+ /**
+ * There is not always a guarantee that Parcelable values will be immediately written out and
+ * read back in. For data data that mutable (its own issue), this can be a problem. This is
+ * for the times when it would be great to have confidence that you will be working with a copy
+ * of that data.
+ */
+ public static Parcelable immediateDeepCopy(Parcelable input) {
+ return immediateDeepCopy(input, input.getClass().getClassLoader());
+ }
+
+ /**
+ * Same as {@link #immediateDeepCopy(android.os.Parcelable)}, but for when you need a little
+ * more control over which ClassLoader will be used.
+ */
+
+ public static Parcelable immediateDeepCopy(Parcelable input, ClassLoader classLoader)
+ {
+ Parcel parcel = null;
+ try
+ {
+ parcel = Parcel.obtain();
+ parcel.writeParcelable(input, 0);
+ parcel.setDataPosition(0);
+ return parcel.readParcelable(classLoader);
+ }
+ finally {
+ if (parcel != null) {
+ parcel.recycle();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/cropper/src/main/java/com/theartofdev/edmodo/cropper/TouchImageView.java b/cropper/src/main/java/com/theartofdev/edmodo/cropper/TouchImageView.java
new file mode 100644
index 00000000..ae093939
--- /dev/null
+++ b/cropper/src/main/java/com/theartofdev/edmodo/cropper/TouchImageView.java
@@ -0,0 +1,1261 @@
+package com.theartofdev.edmodo.cropper;
+
+import android.annotation.TargetApi;
+import android.content.Context;
+import android.content.res.Configuration;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Matrix;
+import android.graphics.PointF;
+import android.graphics.RectF;
+import android.graphics.drawable.Drawable;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Parcelable;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.GestureDetector;
+import android.view.MotionEvent;
+import android.view.ScaleGestureDetector;
+import android.view.View;
+import android.view.animation.AccelerateDecelerateInterpolator;
+import android.widget.ImageView;
+import android.widget.OverScroller;
+import android.widget.Scroller;
+
+/**
+ * Created by ashutoshmishra on 12/10/18.
+ */
+
+public class TouchImageView extends ImageView {
+
+ private static final String DEBUG = "DEBUG";
+
+ //
+ // SuperMin and SuperMax multipliers. Determine how much the image can be
+ // zoomed below or above the zoom boundaries, before animating back to the
+ // min/max zoom boundary.
+ //
+ private static final float SUPER_MIN_MULTIPLIER = .75f;
+ private static final float SUPER_MAX_MULTIPLIER = 1.25f;
+
+ //
+ // Scale of image ranges from minScale to maxScale, where minScale == 1
+ // when the image is stretched to fit view.
+ //
+ private float normalizedScale;
+
+ //
+ // Matrix applied to image. MSCALE_X and MSCALE_Y should always be equal.
+ // MTRANS_X and MTRANS_Y are the other values used. prevMatrix is the matrix
+ // saved prior to the screen rotating.
+ //
+ private Matrix matrix, prevMatrix;
+
+ private static enum State { NONE, DRAG, ZOOM, FLING, ANIMATE_ZOOM };
+ private State state;
+
+ private float minScale;
+ private float maxScale;
+ private float superMinScale;
+ private float superMaxScale;
+ private float[] m;
+
+ private Context context;
+ private Fling fling;
+
+ private ScaleType mScaleType;
+
+ private boolean imageRenderedAtLeastOnce;
+ private boolean onDrawReady;
+
+ private ZoomVariables delayedZoomVariables;
+
+ //
+ // Size of view and previous view size (ie before rotation)
+ //
+ private int viewWidth, viewHeight, prevViewWidth, prevViewHeight;
+
+ //
+ // Size of image when it is stretched to fit view. Before and After rotation.
+ //
+ private float matchViewWidth, matchViewHeight, prevMatchViewWidth, prevMatchViewHeight;
+
+ private ScaleGestureDetector mScaleDetector;
+ private GestureDetector mGestureDetector;
+ private GestureDetector.OnDoubleTapListener doubleTapListener = null;
+ private OnTouchListener userTouchListener = null;
+ private OnTouchImageViewListener touchImageViewListener = null;
+
+ public TouchImageView(Context context) {
+ super(context);
+ sharedConstructing(context);
+ }
+
+ public TouchImageView(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ sharedConstructing(context);
+ }
+
+ public TouchImageView(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ sharedConstructing(context);
+ }
+
+ private void sharedConstructing(Context context) {
+ super.setClickable(true);
+ this.context = context;
+ mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
+ mGestureDetector = new GestureDetector(context, new GestureListener());
+ matrix = new Matrix();
+ prevMatrix = new Matrix();
+ m = new float[9];
+ normalizedScale = 1;
+ if (mScaleType == null) {
+ mScaleType = ScaleType.FIT_CENTER;
+ }
+ minScale = 1;
+ maxScale = 3;
+ superMinScale = SUPER_MIN_MULTIPLIER * minScale;
+ superMaxScale = SUPER_MAX_MULTIPLIER * maxScale;
+ setImageMatrix(matrix);
+ setScaleType(ScaleType.MATRIX);
+ setState(State.NONE);
+ onDrawReady = false;
+ super.setOnTouchListener(new PrivateOnTouchListener());
+ }
+
+ @Override
+ public void setOnTouchListener(View.OnTouchListener l) {
+ userTouchListener = l;
+ }
+
+ public void setOnTouchImageViewListener(OnTouchImageViewListener l) {
+ touchImageViewListener = l;
+ }
+
+ public void setOnDoubleTapListener(GestureDetector.OnDoubleTapListener l) {
+ doubleTapListener = l;
+ }
+
+ @Override
+ public void setImageResource(int resId) {
+ super.setImageResource(resId);
+ savePreviousImageValues();
+ fitImageToView();
+ }
+
+ @Override
+ public void setImageBitmap(Bitmap bm) {
+ super.setImageBitmap(bm);
+ savePreviousImageValues();
+ fitImageToView();
+ }
+
+ @Override
+ public void setImageDrawable(Drawable drawable) {
+ super.setImageDrawable(drawable);
+ savePreviousImageValues();
+ fitImageToView();
+ }
+
+ @Override
+ public void setImageURI(Uri uri) {
+ super.setImageURI(uri);
+ savePreviousImageValues();
+ fitImageToView();
+ }
+
+ @Override
+ public void setScaleType(ScaleType type) {
+ if (type == ScaleType.FIT_START || type == ScaleType.FIT_END) {
+ throw new UnsupportedOperationException("TouchImageView does not support FIT_START or FIT_END");
+ }
+ if (type == ScaleType.MATRIX) {
+ super.setScaleType(ScaleType.MATRIX);
+
+ } else {
+ mScaleType = type;
+ if (onDrawReady) {
+ //
+ // If the image is already rendered, scaleType has been called programmatically
+ // and the TouchImageView should be updated with the new scaleType.
+ //
+ setZoom(this);
+ }
+ }
+ }
+
+ @Override
+ public ScaleType getScaleType() {
+ return mScaleType;
+ }
+
+ /**
+ * Returns false if image is in initial, unzoomed state. False, otherwise.
+ * @return true if image is zoomed
+ */
+ public boolean isZoomed() {
+ return normalizedScale != 1;
+ }
+
+ /**
+ * Return a Rect representing the zoomed image.
+ * @return rect representing zoomed image
+ */
+ public RectF getZoomedRect() {
+ if (mScaleType == ScaleType.FIT_XY) {
+ throw new UnsupportedOperationException("getZoomedRect() not supported with FIT_XY");
+ }
+ PointF topLeft = transformCoordTouchToBitmap(0, 0, true);
+ PointF bottomRight = transformCoordTouchToBitmap(viewWidth, viewHeight, true);
+
+ float w = getDrawable().getIntrinsicWidth();
+ float h = getDrawable().getIntrinsicHeight();
+ return new RectF(topLeft.x / w, topLeft.y / h, bottomRight.x / w, bottomRight.y / h);
+ }
+
+ /**
+ * Save the current matrix and view dimensions
+ * in the prevMatrix and prevView variables.
+ */
+ private void savePreviousImageValues() {
+ if (matrix != null && viewHeight != 0 && viewWidth != 0) {
+ matrix.getValues(m);
+ prevMatrix.setValues(m);
+ prevMatchViewHeight = matchViewHeight;
+ prevMatchViewWidth = matchViewWidth;
+ prevViewHeight = viewHeight;
+ prevViewWidth = viewWidth;
+ }
+ }
+
+ @Override
+ public Parcelable onSaveInstanceState() {
+ Bundle bundle = new Bundle();
+ bundle.putParcelable("instanceState", super.onSaveInstanceState());
+ bundle.putFloat("saveScale", normalizedScale);
+ bundle.putFloat("matchViewHeight", matchViewHeight);
+ bundle.putFloat("matchViewWidth", matchViewWidth);
+ bundle.putInt("viewWidth", viewWidth);
+ bundle.putInt("viewHeight", viewHeight);
+ matrix.getValues(m);
+ bundle.putFloatArray("matrix", m);
+ bundle.putBoolean("imageRendered", imageRenderedAtLeastOnce);
+ return bundle;
+ }
+
+ @Override
+ public void onRestoreInstanceState(Parcelable state) {
+ if (state instanceof Bundle) {
+ Bundle bundle = (Bundle) state;
+ normalizedScale = bundle.getFloat("saveScale");
+ m = bundle.getFloatArray("matrix");
+ prevMatrix.setValues(m);
+ prevMatchViewHeight = bundle.getFloat("matchViewHeight");
+ prevMatchViewWidth = bundle.getFloat("matchViewWidth");
+ prevViewHeight = bundle.getInt("viewHeight");
+ prevViewWidth = bundle.getInt("viewWidth");
+ imageRenderedAtLeastOnce = bundle.getBoolean("imageRendered");
+ super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
+ return;
+ }
+
+ super.onRestoreInstanceState(state);
+ }
+
+ @Override
+ protected void onDraw(Canvas canvas) {
+ onDrawReady = true;
+ imageRenderedAtLeastOnce = true;
+ if (delayedZoomVariables != null) {
+ setZoom(delayedZoomVariables.scale, delayedZoomVariables.focusX, delayedZoomVariables.focusY, delayedZoomVariables.scaleType);
+ delayedZoomVariables = null;
+ }
+ super.onDraw(canvas);
+ }
+
+ @Override
+ public void onConfigurationChanged(Configuration newConfig) {
+ super.onConfigurationChanged(newConfig);
+ savePreviousImageValues();
+ }
+
+ /**
+ * Get the max zoom multiplier.
+ * @return max zoom multiplier.
+ */
+ public float getMaxZoom() {
+ return maxScale;
+ }
+
+ /**
+ * Set the max zoom multiplier. Default value: 3.
+ * @param max max zoom multiplier.
+ */
+ public void setMaxZoom(float max) {
+ maxScale = max;
+ superMaxScale = SUPER_MAX_MULTIPLIER * maxScale;
+ }
+
+ /**
+ * Get the min zoom multiplier.
+ * @return min zoom multiplier.
+ */
+ public float getMinZoom() {
+ return minScale;
+ }
+
+ /**
+ * Get the current zoom. This is the zoom relative to the initial
+ * scale, not the original resource.
+ * @return current zoom multiplier.
+ */
+ public float getCurrentZoom() {
+ return normalizedScale;
+ }
+
+ /**
+ * Set the min zoom multiplier. Default value: 1.
+ * @param min min zoom multiplier.
+ */
+ public void setMinZoom(float min) {
+ minScale = min;
+ superMinScale = SUPER_MIN_MULTIPLIER * minScale;
+ }
+
+ /**
+ * Reset zoom and translation to initial state.
+ */
+ public void resetZoom() {
+ normalizedScale = 1;
+ fitImageToView();
+ }
+
+ /**
+ * Set zoom to the specified scale. Image will be centered by default.
+ * @param scale
+ */
+ public void setZoom(float scale) {
+ setZoom(scale, 0.5f, 0.5f);
+ }
+
+ /**
+ * Set zoom to the specified scale. Image will be centered around the point
+ * (focusX, focusY). These floats range from 0 to 1 and denote the focus point
+ * as a fraction from the left and top of the view. For example, the top left
+ * corner of the image would be (0, 0). And the bottom right corner would be (1, 1).
+ * @param scale
+ * @param focusX
+ * @param focusY
+ */
+ public void setZoom(float scale, float focusX, float focusY) {
+ setZoom(scale, focusX, focusY, mScaleType);
+ }
+
+ /**
+ * Set zoom to the specified scale. Image will be centered around the point
+ * (focusX, focusY). These floats range from 0 to 1 and denote the focus point
+ * as a fraction from the left and top of the view. For example, the top left
+ * corner of the image would be (0, 0). And the bottom right corner would be (1, 1).
+ * @param scale
+ * @param focusX
+ * @param focusY
+ * @param scaleType
+ */
+ public void setZoom(float scale, float focusX, float focusY, ScaleType scaleType) {
+ //
+ // setZoom can be called before the image is on the screen, but at this point,
+ // image and view sizes have not yet been calculated in onMeasure. Thus, we should
+ // delay calling setZoom until the view has been measured.
+ //
+ if (!onDrawReady) {
+ delayedZoomVariables = new ZoomVariables(scale, focusX, focusY, scaleType);
+ return;
+ }
+
+ if (scaleType != mScaleType) {
+ setScaleType(scaleType);
+ }
+ resetZoom();
+ scaleImage(scale, viewWidth / 2, viewHeight / 2, true);
+ matrix.getValues(m);
+ m[Matrix.MTRANS_X] = -((focusX * getImageWidth()) - (viewWidth * 0.5f));
+ m[Matrix.MTRANS_Y] = -((focusY * getImageHeight()) - (viewHeight * 0.5f));
+ matrix.setValues(m);
+ fixTrans();
+ setImageMatrix(matrix);
+ }
+
+ public void setZoom(TouchImageView img) {
+ PointF center = img.getScrollPosition();
+ setZoom(img.getCurrentZoom(), center.x, center.y, img.getScaleType());
+ }
+
+ /**
+ * Return the point at the center of the zoomed image. The PointF coordinates range
+ * in value between 0 and 1 and the focus point is denoted as a fraction from the left
+ * and top of the view. For example, the top left corner of the image would be (0, 0).
+ * And the bottom right corner would be (1, 1).
+ * @return PointF representing the scroll position of the zoomed image.
+ */
+ public PointF getScrollPosition() {
+ Drawable drawable = getDrawable();
+ if (drawable == null) {
+ return null;
+ }
+ int drawableWidth = drawable.getIntrinsicWidth();
+ int drawableHeight = drawable.getIntrinsicHeight();
+
+ PointF point = transformCoordTouchToBitmap(viewWidth / 2, viewHeight / 2, true);
+ point.x /= drawableWidth;
+ point.y /= drawableHeight;
+ return point;
+ }
+
+ /**
+ * Set the focus point of the zoomed image. The focus points are denoted as a fraction from the
+ * left and top of the view. The focus points can range in value between 0 and 1.
+ * @param focusX
+ * @param focusY
+ */
+ public void setScrollPosition(float focusX, float focusY) {
+ setZoom(normalizedScale, focusX, focusY);
+ }
+
+ /**
+ * Performs boundary checking and fixes the image matrix if it
+ * is out of bounds.
+ */
+ private void fixTrans() {
+ matrix.getValues(m);
+ float transX = m[Matrix.MTRANS_X];
+ float transY = m[Matrix.MTRANS_Y];
+
+ float fixTransX = getFixTrans(transX, viewWidth, getImageWidth());
+ float fixTransY = getFixTrans(transY, viewHeight, getImageHeight());
+
+ if (fixTransX != 0 || fixTransY != 0) {
+ matrix.postTranslate(fixTransX, fixTransY);
+ }
+ }
+
+ /**
+ * When transitioning from zooming from focus to zoom from center (or vice versa)
+ * the image can become unaligned within the view. This is apparent when zooming
+ * quickly. When the content size is less than the view size, the content will often
+ * be centered incorrectly within the view. fixScaleTrans first calls fixTrans() and
+ * then makes sure the image is centered correctly within the view.
+ */
+ private void fixScaleTrans() {
+ fixTrans();
+ matrix.getValues(m);
+ if (getImageWidth() < viewWidth) {
+ m[Matrix.MTRANS_X] = (viewWidth - getImageWidth()) / 2;
+ }
+
+ if (getImageHeight() < viewHeight) {
+ m[Matrix.MTRANS_Y] = (viewHeight - getImageHeight()) / 2;
+ }
+ matrix.setValues(m);
+ }
+
+ private float getFixTrans(float trans, float viewSize, float contentSize) {
+ float minTrans, maxTrans;
+
+ if (contentSize <= viewSize) {
+ minTrans = 0;
+ maxTrans = viewSize - contentSize;
+
+ } else {
+ minTrans = viewSize - contentSize;
+ maxTrans = 0;
+ }
+
+ if (trans < minTrans)
+ return -trans + minTrans;
+ if (trans > maxTrans)
+ return -trans + maxTrans;
+ return 0;
+ }
+
+ private float getFixDragTrans(float delta, float viewSize, float contentSize) {
+ if (contentSize <= viewSize) {
+ return 0;
+ }
+ return delta;
+ }
+
+ private float getImageWidth() {
+ return matchViewWidth * normalizedScale;
+ }
+
+ private float getImageHeight() {
+ return matchViewHeight * normalizedScale;
+ }
+
+ @Override
+ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ Drawable drawable = getDrawable();
+ if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) {
+ setMeasuredDimension(0, 0);
+ return;
+ }
+
+ int drawableWidth = drawable.getIntrinsicWidth();
+ int drawableHeight = drawable.getIntrinsicHeight();
+ int widthSize = MeasureSpec.getSize(widthMeasureSpec);
+ int widthMode = MeasureSpec.getMode(widthMeasureSpec);
+ int heightSize = MeasureSpec.getSize(heightMeasureSpec);
+ int heightMode = MeasureSpec.getMode(heightMeasureSpec);
+ viewWidth = setViewSize(widthMode, widthSize, drawableWidth);
+ viewHeight = setViewSize(heightMode, heightSize, drawableHeight);
+
+ //
+ // Set view dimensions
+ //
+ setMeasuredDimension(viewWidth, viewHeight);
+
+ //
+ // Fit content within view
+ //
+ fitImageToView();
+ }
+
+ /**
+ * If the normalizedScale is equal to 1, then the image is made to fit the screen. Otherwise,
+ * it is made to fit the screen according to the dimensions of the previous image matrix. This
+ * allows the image to maintain its zoom after rotation.
+ */
+ private void fitImageToView() {
+ Drawable drawable = getDrawable();
+ if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) {
+ return;
+ }
+ if (matrix == null || prevMatrix == null) {
+ return;
+ }
+
+ int drawableWidth = drawable.getIntrinsicWidth();
+ int drawableHeight = drawable.getIntrinsicHeight();
+
+ //
+ // Scale image for view
+ //
+ float scaleX = (float) viewWidth / drawableWidth;
+ float scaleY = (float) viewHeight / drawableHeight;
+
+ switch (mScaleType) {
+ case CENTER:
+ scaleX = scaleY = 1;
+ break;
+
+ case CENTER_CROP:
+ scaleX = scaleY = Math.max(scaleX, scaleY);
+ break;
+
+ case CENTER_INSIDE:
+ scaleX = scaleY = Math.min(1, Math.min(scaleX, scaleY));
+
+ case FIT_CENTER:
+ scaleX = scaleY = Math.min(scaleX, scaleY);
+ break;
+
+ case FIT_XY:
+ break;
+
+ default:
+ //
+ // FIT_START and FIT_END not supported
+ //
+ throw new UnsupportedOperationException("TouchImageView does not support FIT_START or FIT_END");
+
+ }
+
+ //
+ // Center the image
+ //
+ float redundantXSpace = viewWidth - (scaleX * drawableWidth);
+ float redundantYSpace = viewHeight - (scaleY * drawableHeight);
+ matchViewWidth = viewWidth - redundantXSpace;
+ matchViewHeight = viewHeight - redundantYSpace;
+ if (!isZoomed() && !imageRenderedAtLeastOnce) {
+ //
+ // Stretch and center image to fit view
+ //
+ matrix.setScale(scaleX, scaleY);
+ matrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2);
+ normalizedScale = 1;
+
+ } else {
+ //
+ // These values should never be 0 or we will set viewWidth and viewHeight
+ // to NaN in translateMatrixAfterRotate. To avoid this, call savePreviousImageValues
+ // to set them equal to the current values.
+ //
+ if (prevMatchViewWidth == 0 || prevMatchViewHeight == 0) {
+ savePreviousImageValues();
+ }
+
+ prevMatrix.getValues(m);
+
+ //
+ // Rescale Matrix after rotation
+ //
+ m[Matrix.MSCALE_X] = matchViewWidth / drawableWidth * normalizedScale;
+ m[Matrix.MSCALE_Y] = matchViewHeight / drawableHeight * normalizedScale;
+
+ //
+ // TransX and TransY from previous matrix
+ //
+ float transX = m[Matrix.MTRANS_X];
+ float transY = m[Matrix.MTRANS_Y];
+
+ //
+ // Width
+ //
+ float prevActualWidth = prevMatchViewWidth * normalizedScale;
+ float actualWidth = getImageWidth();
+ translateMatrixAfterRotate(Matrix.MTRANS_X, transX, prevActualWidth, actualWidth, prevViewWidth, viewWidth, drawableWidth);
+
+ //
+ // Height
+ //
+ float prevActualHeight = prevMatchViewHeight * normalizedScale;
+ float actualHeight = getImageHeight();
+ translateMatrixAfterRotate(Matrix.MTRANS_Y, transY, prevActualHeight, actualHeight, prevViewHeight, viewHeight, drawableHeight);
+
+ //
+ // Set the matrix to the adjusted scale and translate values.
+ //
+ matrix.setValues(m);
+ }
+ fixTrans();
+ setImageMatrix(matrix);
+ }
+
+ /**
+ * Set view dimensions based on layout params
+ *
+ * @param mode
+ * @param size
+ * @param drawableWidth
+ * @return
+ */
+ private int setViewSize(int mode, int size, int drawableWidth) {
+ int viewSize;
+ switch (mode) {
+ case MeasureSpec.EXACTLY:
+ viewSize = size;
+ break;
+
+ case MeasureSpec.AT_MOST:
+ viewSize = Math.min(drawableWidth, size);
+ break;
+
+ case MeasureSpec.UNSPECIFIED:
+ viewSize = drawableWidth;
+ break;
+
+ default:
+ viewSize = size;
+ break;
+ }
+ return viewSize;
+ }
+
+ /**
+ * After rotating, the matrix needs to be translated. This function finds the area of image
+ * which was previously centered and adjusts translations so that is again the center, post-rotation.
+ *
+ * @param axis Matrix.MTRANS_X or Matrix.MTRANS_Y
+ * @param trans the value of trans in that axis before the rotation
+ * @param prevImageSize the width/height of the image before the rotation
+ * @param imageSize width/height of the image after rotation
+ * @param prevViewSize width/height of view before rotation
+ * @param viewSize width/height of view after rotation
+ * @param drawableSize width/height of drawable
+ */
+ private void translateMatrixAfterRotate(int axis, float trans, float prevImageSize, float imageSize, int prevViewSize, int viewSize, int drawableSize) {
+ if (imageSize < viewSize) {
+ //
+ // The width/height of image is less than the view's width/height. Center it.
+ //
+ m[axis] = (viewSize - (drawableSize * m[Matrix.MSCALE_X])) * 0.5f;
+
+ } else if (trans > 0) {
+ //
+ // The image is larger than the view, but was not before rotation. Center it.
+ //
+ m[axis] = -((imageSize - viewSize) * 0.5f);
+
+ } else {
+ //
+ // Find the area of the image which was previously centered in the view. Determine its distance
+ // from the left/top side of the view as a fraction of the entire image's width/height. Use that percentage
+ // to calculate the trans in the new view width/height.
+ //
+ float percentage = (Math.abs(trans) + (0.5f * prevViewSize)) / prevImageSize;
+ m[axis] = -((percentage * imageSize) - (viewSize * 0.5f));
+ }
+ }
+
+ private void setState(State state) {
+ this.state = state;
+ }
+
+ public boolean canScrollHorizontallyFroyo(int direction) {
+ return canScrollHorizontally(direction);
+ }
+
+ @Override
+ public boolean canScrollHorizontally(int direction) {
+ matrix.getValues(m);
+ float x = m[Matrix.MTRANS_X];
+
+ if (getImageWidth() < viewWidth) {
+ return false;
+
+ } else if (x >= -1 && direction < 0) {
+ return false;
+
+ } else if (Math.abs(x) + viewWidth + 1 >= getImageWidth() && direction > 0) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Gesture Listener detects a single click or long click and passes that on
+ * to the view's listener.
+ * @author Ortiz
+ *
+ */
+ private class GestureListener extends GestureDetector.SimpleOnGestureListener {
+
+ @Override
+ public boolean onSingleTapConfirmed(MotionEvent e)
+ {
+ if(doubleTapListener != null) {
+ return doubleTapListener.onSingleTapConfirmed(e);
+ }
+ return performClick();
+ }
+
+ @Override
+ public void onLongPress(MotionEvent e)
+ {
+ performLongClick();
+ }
+
+ @Override
+ public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
+ {
+ if (fling != null) {
+ //
+ // If a previous fling is still active, it should be cancelled so that two flings
+ // are not run simultaenously.
+ //
+ fling.cancelFling();
+ }
+ fling = new Fling((int) velocityX, (int) velocityY);
+ compatPostOnAnimation(fling);
+ return super.onFling(e1, e2, velocityX, velocityY);
+ }
+
+ @Override
+ public boolean onDoubleTap(MotionEvent e) {
+ boolean consumed = false;
+ if(doubleTapListener != null) {
+ consumed = doubleTapListener.onDoubleTap(e);
+ }
+ if (state == State.NONE) {
+ float targetZoom = (normalizedScale == minScale) ? maxScale : minScale;
+ DoubleTapZoom doubleTap = new DoubleTapZoom(targetZoom, e.getX(), e.getY(), false);
+ compatPostOnAnimation(doubleTap);
+ consumed = true;
+ }
+ return consumed;
+ }
+
+ @Override
+ public boolean onDoubleTapEvent(MotionEvent e) {
+ if(doubleTapListener != null) {
+ return doubleTapListener.onDoubleTapEvent(e);
+ }
+ return false;
+ }
+ }
+
+ public interface OnTouchImageViewListener {
+ public void onMove();
+ }
+
+ /**
+ * Responsible for all touch events. Handles the heavy lifting of drag and also sends
+ * touch events to Scale Detector and Gesture Detector.
+ * @author Ortiz
+ *
+ */
+ private class PrivateOnTouchListener implements OnTouchListener {
+
+ //
+ // Remember last point position for dragging
+ //
+ private PointF last = new PointF();
+
+ @Override
+ public boolean onTouch(View v, MotionEvent event) {
+ mScaleDetector.onTouchEvent(event);
+ mGestureDetector.onTouchEvent(event);
+ PointF curr = new PointF(event.getX(), event.getY());
+
+ if (state == State.NONE || state == State.DRAG || state == State.FLING) {
+ switch (event.getAction()) {
+ case MotionEvent.ACTION_DOWN:
+ last.set(curr);
+ if (fling != null)
+ fling.cancelFling();
+ setState(State.DRAG);
+ break;
+
+ case MotionEvent.ACTION_MOVE:
+ if (state == State.DRAG) {
+ float deltaX = curr.x - last.x;
+ float deltaY = curr.y - last.y;
+ float fixTransX = getFixDragTrans(deltaX, viewWidth, getImageWidth());
+ float fixTransY = getFixDragTrans(deltaY, viewHeight, getImageHeight());
+ matrix.postTranslate(fixTransX, fixTransY);
+ fixTrans();
+ last.set(curr.x, curr.y);
+ }
+ break;
+
+ case MotionEvent.ACTION_UP:
+ case MotionEvent.ACTION_POINTER_UP:
+ setState(State.NONE);
+ break;
+ }
+ }
+
+ setImageMatrix(matrix);
+
+ //
+ // User-defined OnTouchListener
+ //
+ if(userTouchListener != null) {
+ userTouchListener.onTouch(v, event);
+ }
+
+ //
+ // OnTouchImageViewListener is set: TouchImageView dragged by user.
+ //
+ if (touchImageViewListener != null) {
+ touchImageViewListener.onMove();
+ }
+
+ //
+ // indicate event was handled
+ //
+ return true;
+ }
+ }
+
+ /**
+ * ScaleListener detects user two finger scaling and scales image.
+ * @author Ortiz
+ *
+ */
+ private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
+ @Override
+ public boolean onScaleBegin(ScaleGestureDetector detector) {
+ setState(State.ZOOM);
+ return true;
+ }
+
+ @Override
+ public boolean onScale(ScaleGestureDetector detector) {
+ scaleImage(detector.getScaleFactor(), detector.getFocusX(), detector.getFocusY(), true);
+
+ //
+ // OnTouchImageViewListener is set: TouchImageView pinch zoomed by user.
+ //
+ if (touchImageViewListener != null) {
+ touchImageViewListener.onMove();
+ }
+ return true;
+ }
+
+ @Override
+ public void onScaleEnd(ScaleGestureDetector detector) {
+ super.onScaleEnd(detector);
+ setState(State.NONE);
+ boolean animateToZoomBoundary = false;
+ float targetZoom = normalizedScale;
+ if (normalizedScale > maxScale) {
+ targetZoom = maxScale;
+ animateToZoomBoundary = true;
+
+ } else if (normalizedScale < minScale) {
+ targetZoom = minScale;
+ animateToZoomBoundary = true;
+ }
+
+ if (animateToZoomBoundary) {
+ DoubleTapZoom doubleTap = new DoubleTapZoom(targetZoom, viewWidth / 2, viewHeight / 2, true);
+ compatPostOnAnimation(doubleTap);
+ }
+ }
+ }
+
+ private void scaleImage(double deltaScale, float focusX, float focusY, boolean stretchImageToSuper) {
+
+ float lowerScale, upperScale;
+ if (stretchImageToSuper) {
+ lowerScale = superMinScale;
+ upperScale = superMaxScale;
+
+ } else {
+ lowerScale = minScale;
+ upperScale = maxScale;
+ }
+
+ float origScale = normalizedScale;
+ normalizedScale *= deltaScale;
+ if (normalizedScale > upperScale) {
+ normalizedScale = upperScale;
+ deltaScale = upperScale / origScale;
+ } else if (normalizedScale < lowerScale) {
+ normalizedScale = lowerScale;
+ deltaScale = lowerScale / origScale;
+ }
+
+ matrix.postScale((float) deltaScale, (float) deltaScale, focusX, focusY);
+ fixScaleTrans();
+ }
+
+ /**
+ * DoubleTapZoom calls a series of runnables which apply
+ * an animated zoom in/out graphic to the image.
+ * @author Ortiz
+ *
+ */
+ private class DoubleTapZoom implements Runnable {
+
+ private long startTime;
+ private static final float ZOOM_TIME = 500;
+ private float startZoom, targetZoom;
+ private float bitmapX, bitmapY;
+ private boolean stretchImageToSuper;
+ private AccelerateDecelerateInterpolator interpolator = new AccelerateDecelerateInterpolator();
+ private PointF startTouch;
+ private PointF endTouch;
+
+ DoubleTapZoom(float targetZoom, float focusX, float focusY, boolean stretchImageToSuper) {
+ setState(State.ANIMATE_ZOOM);
+ startTime = System.currentTimeMillis();
+ this.startZoom = normalizedScale;
+ this.targetZoom = targetZoom;
+ this.stretchImageToSuper = stretchImageToSuper;
+ PointF bitmapPoint = transformCoordTouchToBitmap(focusX, focusY, false);
+ this.bitmapX = bitmapPoint.x;
+ this.bitmapY = bitmapPoint.y;
+
+ //
+ // Used for translating image during scaling
+ //
+ startTouch = transformCoordBitmapToTouch(bitmapX, bitmapY);
+ endTouch = new PointF(viewWidth / 2, viewHeight / 2);
+ }
+
+ @Override
+ public void run() {
+ float t = interpolate();
+ double deltaScale = calculateDeltaScale(t);
+ scaleImage(deltaScale, bitmapX, bitmapY, stretchImageToSuper);
+ translateImageToCenterTouchPosition(t);
+ fixScaleTrans();
+ setImageMatrix(matrix);
+
+ //
+ // OnTouchImageViewListener is set: double tap runnable updates listener
+ // with every frame.
+ //
+ if (touchImageViewListener != null) {
+ touchImageViewListener.onMove();
+ }
+
+ if (t < 1f) {
+ //
+ // We haven't finished zooming
+ //
+ compatPostOnAnimation(this);
+
+ } else {
+ //
+ // Finished zooming
+ //
+ setState(State.NONE);
+ }
+ }
+
+ /**
+ * Interpolate between where the image should start and end in order to translate
+ * the image so that the point that is touched is what ends up centered at the end
+ * of the zoom.
+ * @param t
+ */
+ private void translateImageToCenterTouchPosition(float t) {
+ float targetX = startTouch.x + t * (endTouch.x - startTouch.x);
+ float targetY = startTouch.y + t * (endTouch.y - startTouch.y);
+ PointF curr = transformCoordBitmapToTouch(bitmapX, bitmapY);
+ matrix.postTranslate(targetX - curr.x, targetY - curr.y);
+ }
+
+ /**
+ * Use interpolator to get t
+ * @return
+ */
+ private float interpolate() {
+ long currTime = System.currentTimeMillis();
+ float elapsed = (currTime - startTime) / ZOOM_TIME;
+ elapsed = Math.min(1f, elapsed);
+ return interpolator.getInterpolation(elapsed);
+ }
+
+ /**
+ * Interpolate the current targeted zoom and get the delta
+ * from the current zoom.
+ * @param t
+ * @return
+ */
+ private double calculateDeltaScale(float t) {
+ double zoom = startZoom + t * (targetZoom - startZoom);
+ return zoom / normalizedScale;
+ }
+ }
+
+ /**
+ * This function will transform the coordinates in the touch event to the coordinate
+ * system of the drawable that the imageview contain
+ * @param x x-coordinate of touch event
+ * @param y y-coordinate of touch event
+ * @param clipToBitmap Touch event may occur within view, but outside image content. True, to clip return value
+ * to the bounds of the bitmap size.
+ * @return Coordinates of the point touched, in the coordinate system of the original drawable.
+ */
+ private PointF transformCoordTouchToBitmap(float x, float y, boolean clipToBitmap) {
+ matrix.getValues(m);
+ float origW = getDrawable().getIntrinsicWidth();
+ float origH = getDrawable().getIntrinsicHeight();
+ float transX = m[Matrix.MTRANS_X];
+ float transY = m[Matrix.MTRANS_Y];
+ float finalX = ((x - transX) * origW) / getImageWidth();
+ float finalY = ((y - transY) * origH) / getImageHeight();
+
+ if (clipToBitmap) {
+ finalX = Math.min(Math.max(finalX, 0), origW);
+ finalY = Math.min(Math.max(finalY, 0), origH);
+ }
+
+ return new PointF(finalX , finalY);
+ }
+
+ /**
+ * Inverse of transformCoordTouchToBitmap. This function will transform the coordinates in the
+ * drawable's coordinate system to the view's coordinate system.
+ * @param bx x-coordinate in original bitmap coordinate system
+ * @param by y-coordinate in original bitmap coordinate system
+ * @return Coordinates of the point in the view's coordinate system.
+ */
+ private PointF transformCoordBitmapToTouch(float bx, float by) {
+ matrix.getValues(m);
+ float origW = getDrawable().getIntrinsicWidth();
+ float origH = getDrawable().getIntrinsicHeight();
+ float px = bx / origW;
+ float py = by / origH;
+ float finalX = m[Matrix.MTRANS_X] + getImageWidth() * px;
+ float finalY = m[Matrix.MTRANS_Y] + getImageHeight() * py;
+ return new PointF(finalX , finalY);
+ }
+
+ /**
+ * Fling launches sequential runnables which apply
+ * the fling graphic to the image. The values for the translation
+ * are interpolated by the Scroller.
+ * @author Ortiz
+ *
+ */
+ private class Fling implements Runnable {
+
+ CompatScroller scroller;
+ int currX, currY;
+
+ Fling(int velocityX, int velocityY) {
+ setState(State.FLING);
+ scroller = new CompatScroller(context);
+ matrix.getValues(m);
+
+ int startX = (int) m[Matrix.MTRANS_X];
+ int startY = (int) m[Matrix.MTRANS_Y];
+ int minX, maxX, minY, maxY;
+
+ if (getImageWidth() > viewWidth) {
+ minX = viewWidth - (int) getImageWidth();
+ maxX = 0;
+
+ } else {
+ minX = maxX = startX;
+ }
+
+ if (getImageHeight() > viewHeight) {
+ minY = viewHeight - (int) getImageHeight();
+ maxY = 0;
+
+ } else {
+ minY = maxY = startY;
+ }
+
+ scroller.fling(startX, startY, (int) velocityX, (int) velocityY, minX,
+ maxX, minY, maxY);
+ currX = startX;
+ currY = startY;
+ }
+
+ public void cancelFling() {
+ if (scroller != null) {
+ setState(State.NONE);
+ scroller.forceFinished(true);
+ }
+ }
+
+ @Override
+ public void run() {
+
+ //
+ // OnTouchImageViewListener is set: TouchImageView listener has been flung by user.
+ // Listener runnable updated with each frame of fling animation.
+ //
+ if (touchImageViewListener != null) {
+ touchImageViewListener.onMove();
+ }
+
+ if (scroller.isFinished()) {
+ scroller = null;
+ return;
+ }
+
+ if (scroller.computeScrollOffset()) {
+ int newX = scroller.getCurrX();
+ int newY = scroller.getCurrY();
+ int transX = newX - currX;
+ int transY = newY - currY;
+ currX = newX;
+ currY = newY;
+ matrix.postTranslate(transX, transY);
+ fixTrans();
+ setImageMatrix(matrix);
+ compatPostOnAnimation(this);
+ }
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.GINGERBREAD)
+ private class CompatScroller {
+ Scroller scroller;
+ OverScroller overScroller;
+ boolean isPreGingerbread;
+
+ public CompatScroller(Context context) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
+ isPreGingerbread = true;
+ scroller = new Scroller(context);
+
+ } else {
+ isPreGingerbread = false;
+ overScroller = new OverScroller(context);
+ }
+ }
+
+ public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY) {
+ if (isPreGingerbread) {
+ scroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY);
+ } else {
+ overScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY);
+ }
+ }
+
+ public void forceFinished(boolean finished) {
+ if (isPreGingerbread) {
+ scroller.forceFinished(finished);
+ } else {
+ overScroller.forceFinished(finished);
+ }
+ }
+
+ public boolean isFinished() {
+ if (isPreGingerbread) {
+ return scroller.isFinished();
+ } else {
+ return overScroller.isFinished();
+ }
+ }
+
+ public boolean computeScrollOffset() {
+ if (isPreGingerbread) {
+ return scroller.computeScrollOffset();
+ } else {
+ overScroller.computeScrollOffset();
+ return overScroller.computeScrollOffset();
+ }
+ }
+
+ public int getCurrX() {
+ if (isPreGingerbread) {
+ return scroller.getCurrX();
+ } else {
+ return overScroller.getCurrX();
+ }
+ }
+
+ public int getCurrY() {
+ if (isPreGingerbread) {
+ return scroller.getCurrY();
+ } else {
+ return overScroller.getCurrY();
+ }
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
+ private void compatPostOnAnimation(Runnable runnable) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
+ postOnAnimation(runnable);
+
+ } else {
+ postDelayed(runnable, 1000/60);
+ }
+ }
+
+ private class ZoomVariables {
+ public float scale;
+ public float focusX;
+ public float focusY;
+ public ScaleType scaleType;
+
+ public ZoomVariables(float scale, float focusX, float focusY, ScaleType scaleType) {
+ this.scale = scale;
+ this.focusX = focusX;
+ this.focusY = focusY;
+ this.scaleType = scaleType;
+ }
+ }
+
+ private void printMatrixInfo() {
+ float[] n = new float[9];
+ matrix.getValues(n);
+ Log.d(DEBUG, "Scale: " + n[Matrix.MSCALE_X] + " TransX: " + n[Matrix.MTRANS_X] + " TransY: " + n[Matrix.MTRANS_Y]);
+ }
+}
\ No newline at end of file
diff --git a/cropper/src/main/java/com/theartofdev/edmodo/cropper/Util.java b/cropper/src/main/java/com/theartofdev/edmodo/cropper/Util.java
new file mode 100644
index 00000000..ef215893
--- /dev/null
+++ b/cropper/src/main/java/com/theartofdev/edmodo/cropper/Util.java
@@ -0,0 +1,234 @@
+package com.theartofdev.edmodo.cropper;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Matrix;
+import android.net.Uri;
+import android.util.Log;
+
+import androidx.exifinterface.media.ExifInterface;
+
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Created by root on 9/14/17.
+ */
+
+public class Util
+{
+ public static Uri getCompressed(Context context, Uri path, CropImageOptions options) throws IOException
+ {
+ if(context == null)
+ throw new NullPointerException("Context must not be null.");
+
+ Uri outputUri = options.outputUri;
+ if (outputUri == null || outputUri.equals(Uri.EMPTY))
+ {
+ try
+ {
+ String ext = options.outputCompressFormat == Bitmap.CompressFormat.JPEG ? ".jpg" : options.outputCompressFormat == Bitmap.CompressFormat.PNG ? ".png" : ".webp";
+ outputUri = Uri.fromFile(File.createTempFile("cropped", ext, context.getCacheDir()));
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to create temp file for output image", e);
+ }
+ }
+
+ int rotation = rotateByExif(context, path);
+ Bitmap bitmap = decodeImageFromFiles(context, path, options.outputRequestWidth, options.outputRequestHeight, rotation);
+
+ //create placeholder for the compressed image file
+ File compressed = new File(outputUri.getPath());
+
+ //convert the decoded bitmap to stream
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+
+ bitmap.compress(options.outputCompressFormat, options.outputCompressQuality, byteArrayOutputStream);
+
+ FileOutputStream fileOutputStream = new FileOutputStream(compressed);
+ fileOutputStream.write(byteArrayOutputStream.toByteArray());
+ fileOutputStream.flush();
+ fileOutputStream.close();
+
+
+ //File written, return to the caller. Done!
+ return Uri.fromFile(compressed);
+ }
+
+ private static Bitmap decodeImageFromFiles(Context context, Uri path, int requestedwidth, int requestedHeight, int rotation)
+ {
+ Log.d("fatal", "File path : " + path);
+
+ InputStream stream = null;
+ Bitmap bitmap = null;
+
+ try
+ {
+ stream = context.getContentResolver().openInputStream(path);
+ bitmap = BitmapFactory.decodeStream(stream);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ closeSafe(stream);
+ }
+
+ Bitmap output = resizeBitmap(bitmap, requestedwidth, requestedHeight, rotation);
+
+ Matrix m = new Matrix();
+ m.setRotate(rotation, (float) output.getWidth() / 2, (float) output.getHeight() / 2);
+
+ return Bitmap.createBitmap(output, 0, 0, output.getWidth(), output.getHeight(), m, true);
+ }
+
+ /** Resize the given bitmap to the given width/height by the given option.
*/
+ private static Bitmap resizeBitmap(Bitmap bitmap, int reqWidth, int reqHeight, int rotation)
+ {
+ try
+ {
+ if (reqWidth > 0 && reqHeight > 0)
+ {
+ Bitmap resized = null;
+ int width = bitmap.getWidth();
+ int height = bitmap.getHeight();
+ float scale = Math.max(width / (float) reqWidth, height / (float) reqHeight);
+
+ if (scale > 1)
+ resized = Bitmap.createScaledBitmap(bitmap, (int) (width / scale), (int) (height / scale), false);
+
+ if (resized != null)
+ {
+ if (resized != bitmap)
+ bitmap.recycle();
+ return resized;
+ }
+ }
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ Log.d("fatal", "Failed to resize cropped image, return bitmap before resize");
+ }
+
+ return bitmap;
+ }
+
+ private static int rotateByExif(Context context, Uri uri)
+ {
+ ExifInterface ei = null;
+ InputStream is = null;
+ try
+ {
+ is = context.getContentResolver().openInputStream(uri);
+ if (is != null)
+ ei = new ExifInterface(is);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ finally {
+ closeSafe(is);
+ }
+ return ei != null ? rotateBitmapByExif(ei) : 0;
+ }
+
+ /**
+ * Rotate the given image by given Exif value.
+ * If no rotation is required the image will not be rotated.
+ * New bitmap is created and the old one is recycled.
+ */
+ private static int rotateBitmapByExif(ExifInterface exif)
+ {
+ int degrees;
+ int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
+ switch (orientation)
+ {
+ case ExifInterface.ORIENTATION_ROTATE_90:
+ degrees = 90;
+ break;
+ case ExifInterface.ORIENTATION_ROTATE_180:
+ degrees = 180;
+ break;
+ case ExifInterface.ORIENTATION_ROTATE_270:
+ degrees = 270;
+ break;
+ default:
+ degrees = 0;
+ break;
+ }
+ return degrees;
+ }
+
+
+ private static void closeSafe(Closeable closeable)
+ {
+ if (closeable != null) {
+ try {
+ closeable.close();
+ } catch (IOException ignored) {
+ }
+ }
+ }
+
+ public static Bitmap decodeSampledBitmapFromResource(Context context, Uri uri, int reqWidth, int reqHeight)
+ {
+ Log.d("fatal", "File path : " + uri);
+
+ InputStream stream = null;
+ Bitmap bitmap = null;
+ final BitmapFactory.Options options = new BitmapFactory.Options();
+
+ try
+ {
+ stream = context.getContentResolver().openInputStream(uri);
+ options.inJustDecodeBounds = true;
+ BitmapFactory.decodeStream(stream, null, options);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ closeSafe(stream);
+ }
+
+ try
+ {
+ stream = context.getContentResolver().openInputStream(uri);
+ options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
+ options.inJustDecodeBounds = false;
+ bitmap = BitmapFactory.decodeStream(stream, null, options);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ closeSafe(stream);
+ }
+
+ return bitmap;
+ }
+
+ private static int calculateInSampleSize (BitmapFactory.Options options, int reqWidth, int reqHeight)
+ {
+ // Raw height and width of image
+ final int height = options.outHeight;
+ final int width = options.outWidth;
+ int inSampleSize = 1;
+
+ if (height > reqHeight || width > reqWidth)
+ {
+ final int halfHeight = height / 2;
+ final int halfWidth = width / 2;
+
+ // Calculate the largest inSampleSize value that is a power of 2 and keeps both
+ // height and width larger than the requested height and width.
+ while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
+ inSampleSize *= 2;
+ }
+ }
+
+ return inSampleSize;
+ }
+}
\ No newline at end of file
diff --git a/cropper/src/main/res/drawable-xhdpi/placeholder.png b/cropper/src/main/res/drawable-xhdpi/placeholder.png
new file mode 100644
index 00000000..e6e212ca
Binary files /dev/null and b/cropper/src/main/res/drawable-xhdpi/placeholder.png differ
diff --git a/cropper/src/main/res/layout/activity_crop_images.xml b/cropper/src/main/res/layout/activity_crop_images.xml
new file mode 100644
index 00000000..79efab05
--- /dev/null
+++ b/cropper/src/main/res/layout/activity_crop_images.xml
@@ -0,0 +1,38 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/cropper/src/main/res/layout/crop_media_tab.xml b/cropper/src/main/res/layout/crop_media_tab.xml
new file mode 100644
index 00000000..1f751318
--- /dev/null
+++ b/cropper/src/main/res/layout/crop_media_tab.xml
@@ -0,0 +1,8 @@
+
+
\ No newline at end of file
diff --git a/cropper/src/main/res/menu/menu_crop_images.xml b/cropper/src/main/res/menu/menu_crop_images.xml
new file mode 100644
index 00000000..833be7d9
--- /dev/null
+++ b/cropper/src/main/res/menu/menu_crop_images.xml
@@ -0,0 +1,15 @@
+
+
\ No newline at end of file
diff --git a/cropper/src/main/res/values/colors.xml b/cropper/src/main/res/values/colors.xml
new file mode 100644
index 00000000..f380407a
--- /dev/null
+++ b/cropper/src/main/res/values/colors.xml
@@ -0,0 +1,4 @@
+
+
+ #fff8e5
+
\ No newline at end of file
diff --git a/cropper/src/main/res/values/strings.xml b/cropper/src/main/res/values/strings.xml
index 6dc1fd22..5bf1edaf 100644
--- a/cropper/src/main/res/values/strings.xml
+++ b/cropper/src/main/res/values/strings.xml
@@ -8,7 +8,7 @@
Flip
Flip horizontally
Flip vertically
-
+ Done
Select source
Cancelling, required permissions are not granted
diff --git a/sample/src/main/AndroidManifest.xml b/sample/src/main/AndroidManifest.xml
index 12af57e2..96e4c996 100644
--- a/sample/src/main/AndroidManifest.xml
+++ b/sample/src/main/AndroidManifest.xml
@@ -25,6 +25,11 @@
+
+
+
+
+
diff --git a/sample/src/main/java/com/theartofdev/edmodo/cropper/sample/AddMultiplePhotos.java b/sample/src/main/java/com/theartofdev/edmodo/cropper/sample/AddMultiplePhotos.java
new file mode 100644
index 00000000..1a42ff74
--- /dev/null
+++ b/sample/src/main/java/com/theartofdev/edmodo/cropper/sample/AddMultiplePhotos.java
@@ -0,0 +1,115 @@
+package com.theartofdev.edmodo.cropper.sample;
+
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.appcompat.widget.AppCompatButton;
+
+import com.example.croppersample.R;
+import com.theartofdev.edmodo.cropper.CropImageView;
+import com.theartofdev.edmodo.cropper.CropImages;
+
+import java.io.File;
+import java.util.ArrayList;
+
+public class AddMultiplePhotos extends AppCompatActivity
+{
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState)
+ {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_add_multiple);
+ setupViews();
+ }
+
+ public void setupViews()
+ {
+ AppCompatButton clickHere = findViewById(R.id.click_here);
+ clickHere.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ createIntentChooser();
+ }
+ });
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data)
+ {
+ super.onActivityResult(requestCode, resultCode, data);
+
+ if (requestCode == CropImages.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
+ {
+ CropImages.ActivityResult result = CropImages.getActivityResult(data);
+ if (resultCode == RESULT_OK)
+ {
+ ArrayList resultUri = result.getResultUri();
+ Log.d("fatal", "New photo size ==> " + resultUri.toString()); //log new file size.
+ }
+ else if (resultCode == CropImages.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
+ {
+ Exception error = result.getError();
+ error.printStackTrace();
+ Log.d("fatal", "Some error occurred "); //log new file size.
+ }
+ else
+ {
+ Log.d("fatal", "Back button pressed"); //log new file size.
+ }
+ }
+ }
+
+ private void createIntentChooser() {
+ // start picker to get image for cropping and then use the image in cropping activity
+ CropImages.activity()
+ .setGuidelines(CropImageView.Guidelines.ON)
+ .setAllowRotation(true)
+ .setAllowCounterRotation(true)
+ .setRequestedSize(1920, 1920)
+ .setAllowFlipping(false)
+ .setAutoZoomEnabled(true)
+ .setMinCropResultSize(480, 480)
+ .setMinCropWindowSize(480, 480)
+ .start(this);
+ }
+
+ public static void deleteCache(Context context)
+ {
+ try
+ {
+ File dir = context.getCacheDir();
+ deleteFiles(dir, "cropped");
+
+ File extDir = context.getExternalCacheDir();
+ deleteFiles(extDir, "pick");
+
+ }
+ catch (Exception e) {}
+ }
+
+ private static void deleteFiles(File dir, String name)
+ {
+ if (dir != null && dir.isDirectory())
+ {
+ File[] children = dir.listFiles();
+ for (File ff: children)
+ {
+ if(ff.isFile() && ff.getName().startsWith(name))
+ ff.delete();
+ }
+ }
+ }
+
+ @Override
+ protected void onDestroy()
+ {
+ deleteCache(AddMultiplePhotos.this);
+ super.onDestroy();
+ }
+}
\ No newline at end of file
diff --git a/sample/src/main/java/com/theartofdev/edmodo/cropper/sample/MainActivity.java b/sample/src/main/java/com/theartofdev/edmodo/cropper/sample/MainActivity.java
index 44d3f34d..c6a0683c 100644
--- a/sample/src/main/java/com/theartofdev/edmodo/cropper/sample/MainActivity.java
+++ b/sample/src/main/java/com/theartofdev/edmodo/cropper/sample/MainActivity.java
@@ -169,6 +169,11 @@ public void onDrawerOptionClicked(View view) {
}
mDrawerLayout.closeDrawers();
break;
+ case R.id.drawer_option_load_multiple:
+ Intent intent = new Intent(MainActivity.this, AddMultiplePhotos.class);
+ startActivity(intent);
+ mDrawerLayout.closeDrawers();
+ break;
case R.id.drawer_option_oval:
setMainFragmentByPreset(CropDemoPreset.CIRCULAR);
mDrawerLayout.closeDrawers();
diff --git a/sample/src/main/res/layout/activity_add_multiple.xml b/sample/src/main/res/layout/activity_add_multiple.xml
new file mode 100644
index 00000000..cef57c6d
--- /dev/null
+++ b/sample/src/main/res/layout/activity_add_multiple.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sample/src/main/res/layout/activity_main.xml b/sample/src/main/res/layout/activity_main.xml
index c714b8f7..b5131309 100644
--- a/sample/src/main/res/layout/activity_main.xml
+++ b/sample/src/main/res/layout/activity_main.xml
@@ -36,6 +36,12 @@
android:onClick="onDrawerOptionClicked"
android:text="@string/main_drawer_load"/>
+
+
crop result
Load Image for cropping
+ Load Multiple Images
Open navigation drawer
Close navigation drawer