Exemplo n.º 1
0
 public override void OnActivityResult(int requestCode, int resultCode, Intent data)
 {
     base.OnActivityResult(requestCode, resultCode, data);
     try
     {
         if (resultCode == (int)Result.Ok)
         {
             if (requestCode == SELECT_PICTURE)
             {
                 Uri selectedImageURI = data.Data;
                 CropImage(selectedImageURI);
             }
             else if (requestCode == REQUEST_IMAGE_CAPTURE)
             {
                 CropImage(GetCacheImagePath(fileName));
             }
             else if (requestCode == UCrop.RequestCrop)
             {
                 uri = UCrop.GetOutput(data);
                 Glide.With(this).Load(uri).Into(postImageView);
                 hasImage        = true;
                 doneBtn.Enabled = commentEt.EditText.Text.Length >= 6 && hasImage;
             }
             else if (requestCode == UCrop.ResultError)
             {
                 throw UCrop.GetError(data);
             }
         }
     }
     catch (System.Exception)
     {
     }
 }
Exemplo n.º 2
0
        // Optional parameters for calling this method from viewHolder
        public void StartCropActivity(Android.Net.Uri uri, Activity context = null, int pressedPhotoPos = 0)
        {
            UCrop uCrop;

            _pressedPhotoPosition = pressedPhotoPos;
            if (context != null)
            {
                uCrop = UCrop.Of(uri, Android.Net.Uri.FromFile(new Java.IO.File(context.CacheDir, Constants.destinationFileName)));
            }
            else
            {
                uCrop = UCrop.Of(uri, Android.Net.Uri.FromFile(new Java.IO.File(CacheDir, Constants.destinationFileName)));
            }
            uCrop.WithAspectRatio(1, 1);

            uCrop.WithOptions(_nativeMethods.UCropOptions());

            if (context != null)
            {
                uCrop.Start(context);
            }
            else
            {
                uCrop.Start(this);
            }
        }
 public override void OnActivityResult(int requestCode, int resultCode, Intent data)
 {
     base.OnActivityResult(requestCode, resultCode, data);
     try
     {
         if (resultCode == (int)Result.Ok)
         {
             if (requestCode == SELECT_PICTURE)
             {
                 Uri selectedImageURI = data.Data;
                 CropImage(selectedImageURI);
             }
             else if (requestCode == REQUEST_IMAGE_CAPTURE)
             {
                 CropImage(GetCacheImagePath(fileName));
             }
             else if (requestCode == UCrop.RequestCrop)
             {
                 var uri = UCrop.GetOutput(data);
                 OnCropComplete?.Invoke(this, new CropCompleteEventArgs {
                     imageUri = uri
                 });
                 DismissAllowingStateLoss();
             }
             else if (requestCode == UCrop.ResultError)
             {
                 throw UCrop.GetError(data);
             }
         }
     }
     catch (System.Exception)
     {
     }
 }
Exemplo n.º 4
0
        private UCrop BasisConfig(UCrop uCrop)
        {
            switch (mRadioGroupAspectRatio.CheckedRadioButtonId)
            {
            case Resource.Id.radio_origin:
                uCrop = uCrop.UseSourceImageAspectRatio();

                break;

            case Resource.Id.radio_square:
                uCrop = uCrop.WithAspectRatio(1, 1);

                break;

            case Resource.Id.radio_dynamic:
                // do nothing
                break;

            default:
                try
                {
                    float ratioX = float.Parse(mEditTextRatioX.Text.Trim());
                    float ratioY = float.Parse(mEditTextRatioY.Text.Trim());
                    if (ratioX > 0 && ratioY > 0)
                    {
                        uCrop = uCrop.WithAspectRatio(ratioX, ratioY);
                    }
                }
                catch (NumberFormatException e)
                {
                    System.Diagnostics.Debug.WriteLine(e.Message);
                }

                break;
            }

            if (mCheckBoxMaxSize.Checked)
            {
                try
                {
                    int maxWidth  = int.Parse(mEditTextMaxWidth.Text.Trim());
                    int maxHeight = int.Parse(mEditTextMaxHeight.Text.Trim());
                    if (maxWidth > 0 && maxHeight > 0)
                    {
                        uCrop = uCrop.WithMaxResultSize(maxWidth, maxHeight);
                    }
                }
                catch (NumberFormatException e)
                {
                    System.Diagnostics.Debug.WriteLine(e.Message);
                }
            }

            return(uCrop);
        }
Exemplo n.º 5
0
 private void HandleCropResult(Intent result)
 {
     Android.Net.Uri resultUri = UCrop.GetOutput(result);
     if (resultUri != null)
     {
         ResultActivity.StartWithUri(this, resultUri);
     }
     else
     {
         Toast.MakeText(this, Resource.String.toast_cannot_retrieve_cropped_image, ToastLength.Short).Show();
     }
 }
Exemplo n.º 6
0
        private void HandleActivityResultOK(RequestCode requestCode, Intent data)
        {
            switch (requestCode)
            {
            case RequestCode.ImageOpen:
                // ImageInput -> Photo Library/Camera -> Crop -> Analysis -> Results
                //                                    ^^
                //                              this transition
                //

                // Launch Crop
                originalImageUri = data.Data;
                TryExtStorageDependentAction(LaunchPhotoCropper);
                RunForwardAnimation();
                break;

            case RequestCode.Camera:
                // ImageInput -> Photo Library/Camera -> Crop -> Analysis -> Results
                //                                    ^^
                //                              this transition
                //

                // Launch Crop (originalImageUri got set when we launched the camera)
                TryExtStorageDependentAction(LaunchPhotoCropper);
                RunForwardAnimation();
                break;

            case RequestCode.Crop:
                // ImageInput -> Photo Library/Camera -> Crop -> Analysis -> Results
                //                                            ^^
                //                                      this transition
                //

                // Launch Analysis
                AndroidUri croppedImageUri = UCrop.GetOutput(data);
                LaunchAnalysis(croppedImageUri);
                RunForwardAnimation();
                break;

            case RequestCode.Analysis:
                // ImageInput -> Photo Library/Camera -> Crop -> Analysis -> Results
                //                                                        ^^
                //                                                  this transition
                //

                // Launch Analysis
                LaunchResults(data);
                RunForwardAnimation();
                break;
            }
        }
Exemplo n.º 7
0
        private void HandleCropError(Intent result)
        {
            Throwable cropError = UCrop.GetError(result);

            if (cropError != null)
            {
                System.Diagnostics.Debug.WriteLine(cropError.Message);
                Toast.MakeText(this, cropError.Message, ToastLength.Long).Show();
            }
            else
            {
                Toast.MakeText(this, Resource.String.toast_unexpected_error, ToastLength.Short).Show();
            }
        }
Exemplo n.º 8
0
        private void CropImage()
        {
            var croppedFile    = CreateTempFile(_cacheDir, "cropped");
            var destinationUri = AndroidUri.FromFile(croppedFile);
            var options        = new UCrop.Options();

            // applying UI theme
            options.SetToolbarColor(ContextCompat.GetColor(this, Resource.Color.colorPrimary));
            options.SetStatusBarColor(ContextCompat.GetColor(this, Resource.Color.colorPrimary));
            options.SetActiveControlsWidgetColor(ContextCompat.GetColor(this, Resource.Color.colorPrimary));
            options.WithAspectRatio(1, 1);
            options.WithMaxResultSize(2000, 2000);
            options.SetCompressionQuality(80);

            UCrop.Of(_photoUri, destinationUri)
            .WithOptions(options)
            .Start(this);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Launches the photo cropper.
        /// </summary>
        /// <param name="sourceUri">The URI of the source image.</param>
        /// <param name="activity">An <see cref="Activity"/> to use to obtain resources.</param>
        /// <returns>The URI where the cropped image will be saved.</returns>
        public static AndroidUri LaunchPhotoCropper(AndroidUri sourceUri, Activity activity)
        {
            File       dest    = new File(activity.CacheDir, FILENAME_CROPPED_IMAGE);
            AndroidUri destUri = AndroidUri.FromFile(dest);

            UCrop.Options options = new UCrop.Options();
            options.SetCompressionFormat(Bitmap.CompressFormat.Png);
            options.SetToolbarColor(ContextCompat.GetColor(activity, Resource.Color.color_primary));
            options.SetStatusBarColor(ContextCompat.GetColor(activity, Resource.Color.color_primary_dark));
            options.SetActiveWidgetColor(ContextCompat.GetColor(activity, Resource.Color.color_accent));
            options.SetToolbarTitle(activity.GetString(Resource.String.crop_title));

            UCrop.Of(sourceUri, destUri)
            .WithAspectRatio(1, 1)
            .WithOptions(options)
            .Start(activity);

            return(destUri);
        }
Exemplo n.º 10
0
        private void HandleActivityResultError(RequestCode requestCode, Intent data)
        {
            switch (requestCode)
            {
            case RequestCode.ImageOpen:
                System.Diagnostics.Debug.WriteLine("RequestImageOpen error");
                Snackbar.Make(rootView, Resource.String.image_input_result_error, Snackbar.LengthIndefinite).SetAction(Android.Resource.String.Ok, (v) => { }).Show();
                break;

            case RequestCode.Camera:
                Snackbar.Make(rootView, Resource.String.camera_result_error, Snackbar.LengthIndefinite).SetAction(Android.Resource.String.Ok, (v) => { }).Show();
                break;

            case RequestCode.Crop:
                Java.Lang.Throwable cropError = UCrop.GetError(data);
                cropError.PrintStackTrace();
                Snackbar.Make(rootView, Resource.String.crop_result_error, Snackbar.LengthIndefinite).SetAction(Android.Resource.String.Ok, (v) => { }).Show();
                break;
            }
        }
Exemplo n.º 11
0
        private void StartCropActivity(Android.Net.Uri uri)
        {
            string destinationFileName = SAMPLE_CROPPED_IMAGE_NAME;

            switch (mRadioGroupCompressionSettings.CheckedRadioButtonId)
            {
            case Resource.Id.radio_png:
                destinationFileName += ".png";
                break;

            case Resource.Id.radio_jpeg:
                destinationFileName += ".jpg";
                break;
            }

            UCrop uCrop = UCrop.Of(uri, Android.Net.Uri.FromFile(new Java.IO.File(CacheDir, destinationFileName)));

            uCrop = BasisConfig(uCrop);
            uCrop = AdvancedConfig(uCrop);

            uCrop.Start(this);
        }
Exemplo n.º 12
0
        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            switch (requestCode)
            {
            case RequestCamera when resultCode == Result.Ok:
                CropImage();
                break;

            case RequestGallery when resultCode == Result.Ok && data != null:
                _photoUri = data.Data;

                CropImage();
                break;

            case UCrop.RequestCrop when resultCode == Result.Ok:
                if (data == null)
                {
                    return;
                }

                var croppedImageUri = UCrop.GetOutput(data);

                _ivResult.SetImageURI(croppedImageUri);
                break;

            case UCrop.ResultError:
            case 69:
                var error = UCrop.GetError(data);

                Log.Error("error", error.ToString());

                Toast.MakeText(this, "Failed to crop image.", ToastLength.Long).Show();
                break;

            default:
                Toast.MakeText(this, "Request has cancelled.", ToastLength.Long).Show();
                break;
            }
        }
Exemplo n.º 13
0
        private void CropImage(Uri selectedImageURI)
        {
            Uri destinationUri = Uri.FromFile(new File(Context.CacheDir, QueryName(Context.ContentResolver, selectedImageURI)));

            UCrop.Options options = new UCrop.Options();
            options.SetCompressionQuality(IMAGE_COMPRESSION);
            options.SetToolbarColor(ContextCompat.GetColor(Context, Resource.Color.colorPrimary));
            options.SetStatusBarColor(ContextCompat.GetColor(Context, Resource.Color.colorPrimaryDark));
            options.SetActiveControlsWidgetColor(ContextCompat.GetColor(Context, Resource.Color.colorAccent));

            if (lockAspectRatio)
            {
                options.WithAspectRatio(ASPECT_RATIO_X, ASPECT_RATIO_Y);
            }

            if (setBitmapMaxWidthHeight)
            {
                options.WithMaxResultSize(bitmapMaxWidth, bitmapMaxHeight);
            }

            UCrop.Of(selectedImageURI, destinationUri)
            .WithOptions(options)
            .Start(Context, this, UCROP_REQUEST);
        }
Exemplo n.º 14
0
        private UCrop AdvancedConfig(UCrop uCrop)
        {
            UCrop.Options options = new UCrop.Options();

            switch (mRadioGroupCompressionSettings.CheckedRadioButtonId)
            {
            case Resource.Id.radio_png:
                options.SetCompressionFormat(Bitmap.CompressFormat.Png);

                break;

            case Resource.Id.radio_jpeg:

            default:
                options.SetCompressionFormat(Bitmap.CompressFormat.Jpeg);

                break;
            }
            options.SetCompressionQuality(mSeekBarQuality.Progress);

            options.SetHideBottomControls(mCheckBoxHideBottomControls.Checked);
            options.SetFreeStyleCropEnabled(mCheckBoxFreeStyleCrop.Checked);

            /*
             * If you want to configure how gestures work for all UCropActivity tabs
             *
             * options.SetAllowedGestures(UCropActivity.Scale, UCropActivity.Rotate, UCropActivity.All);
             *
             * */

            /*
             * This sets max size for bitmap that will be decoded from source Uri.
             * More size - more memory allocation, default implementation uses screen diagonal.
             *
             * options.SetMaxBitmapSize(640);
             *
             * */


            /*
             *
             * Tune everything
             *
             * options.SetMaxScaleMultiplier(5);
             * options.SetImageToCropBoundsAnimDuration(666);
             * options.SetDimmedLayerColor(Color.Cyan);
             * options.SetCircleDimmedLayer(true);
             * options.SetShowCropFrame(false);
             * options.SetCropGridStrokeWidth(20);
             * options.SetCropGridColor(Color.Green);
             * options.SetCropGridColumnCount(2);
             * options.SetCropGridRowCount(1);
             *
             * // not found two below methods
             * //options.SetToolbarCropDrawable(Resource.Drawable.your_crop_icon);
             * //options.SetToolbarCancelDrawable(Resource.Drawable.your_cancel_icon);
             *
             * // Color palette
             * //options.SetToolbarColor(ContextCompat.GetColor(this, Resource.Color.your_color_res));
             * //options.SetStatusBarColor(ContextCompat.GetColor(this, Resource.Color.your_color_res));
             * //options.SetActiveWidgetColor(ContextCompat.GetColor(this, Resource.Color.your_color_res));
             * //options.SetToolbarWidgetColor(ContextCompat.GetColor(this, Resource.Color.your_color_res));
             *
             * // not found the below method
             * //options.SetRootViewBackgroundColor(ContextCompat.getColor(this, R.color.your_color_res));
             *
             * // Aspect ratio options
             * options.SetAspectRatioOptions(1,
             *   new AspectRatio("WOW", 1, 2),
             *   new AspectRatio("MUCH", 3, 4),
             *   new AspectRatio("RATIO", CropImageView.DefaultAspectRatio, CropImageView.DefaultAspectRatio),
             *   new AspectRatio("SO", 16, 9),
             *   new AspectRatio("ASPECT", 1, 1));
             *
             */

            return(uCrop.WithOptions(options));
        }
Exemplo n.º 15
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            if (requestCode == UCrop.RequestCrop)
            {
                if (data != null)
                {
                    Android.Net.Uri resultUri = UCrop.GetOutput(data);
                    if (resultUri != null)
                    {
                        try
                        {
                            if (_pressedPhotoPosition == 0)
                            {
                                PersonalImageAdapter.Photos.Add(NativeMethods.GetBitmapFromUrl(resultUri.Path));
                            }
                            else
                            {
                                PersonalImageAdapter.Photos.RemoveAt(_pressedPhotoPosition);
                                PersonalImageAdapter.Photos.Insert(_pressedPhotoPosition, NativeMethods.GetBitmapFromUrl(resultUri.Path));
                            }
                        }
                        catch (Exception ex)
                        {
                            if (!_methods.IsConnected())
                            {
                                NoConnectionActivity.ActivityName = this;
                                StartActivity(typeof(NoConnectionActivity));
                                Finish();
                                return;
                            }
                        }
                    }
                }

                _personalImageAdapter.NotifyDataSetChanged();
                return;
            }
            if (PictureMethods.CameraOrGalleryIndicator == Constants.gallery)
            {
                if (resultCode == Result.Ok)
                {
                    //FindViewById<ImageView>(Resource.Id.imageView1).SetImageURI(data.Data);
                    var res = CheckStoragePermissions();
                    if (!res.Result)
                    {
                        return;
                    }
                    try
                    {
                        StartCropActivity(data.Data);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            else if (PictureMethods.CameraOrGalleryIndicator == Constants.camera)
            {
                int height = Resources.DisplayMetrics.HeightPixels;
                int width  = Resources.DisplayMetrics.WidthPixels;
                var path   = App.File.Path;

                Android.Net.Uri uri   = Android.Net.Uri.FromFile(new Java.IO.File(path));
                Stream          input = null;
                try
                {
                    input = this.ContentResolver.OpenInputStream(uri);
                }
                catch (Exception ex)
                {
                    var res = CheckStoragePermissions();
                    if (!res.Result)
                    {
                        return;
                    }
                }
                ////Use bitarray to use less memory
                //byte[] buffer = new byte[16 * 1024];
                //byte[] pictByteArray;

                if (input == null)
                {
                    //Toast.MakeText(this, TranslationHelper.GetString("permissionsNeeded", ci), ToastLength.Long).Show();
                    //Task.Delay(1000);
                    return;
                }

                //using (MemoryStream ms = new MemoryStream())
                //{
                //    int read;
                //    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                //    {
                //        ms.Write(buffer, 0, read);
                //    }
                //    pictByteArray = ms.ToArray();
                //}

                input.Close();
                // Dispose of the Java side bitmap.
                GC.Collect();
                try
                {
                    StartCropActivity(uri);
                }
                catch (Exception ex)
                {
                }
            }
        }