forked from yasirkula/UnityImageCropper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImageCropperDemo.cs
89 lines (75 loc) · 2.69 KB
/
ImageCropperDemo.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace ImageCropperNamespace
{
public class ImageCropperDemo : MonoBehaviour
{
public RawImage croppedImageHolder;
public Text croppedImageSize;
public Toggle ovalSelectionInput, autoZoomInput;
public InputField minAspectRatioInput, maxAspectRatioInput;
public void Crop()
{
// If image cropper is already open, do nothing
if( ImageCropper.Instance.IsOpen )
return;
StartCoroutine( TakeScreenshotAndCrop() );
}
private IEnumerator TakeScreenshotAndCrop()
{
yield return new WaitForEndOfFrame();
bool ovalSelection = ovalSelectionInput.isOn;
bool autoZoom = autoZoomInput.isOn;
float minAspectRatio, maxAspectRatio;
if( !float.TryParse( minAspectRatioInput.text, out minAspectRatio ) )
minAspectRatio = 0f;
if( !float.TryParse( maxAspectRatioInput.text, out maxAspectRatio ) )
maxAspectRatio = 0f;
Texture2D screenshot = new Texture2D( Screen.width, Screen.height, TextureFormat.RGB24, false );
screenshot.ReadPixels( new Rect( 0, 0, Screen.width, Screen.height ), 0, 0 );
screenshot.Apply();
ImageCropper.Instance.Show( screenshot, ( bool result, Texture originalImage, Texture2D croppedImage ) =>
{
// Destroy previously cropped texture (if any) to free memory
Destroy( croppedImageHolder.texture, 5f );
// If screenshot was cropped successfully
if( result )
{
// Assign cropped texture to the RawImage
croppedImageHolder.enabled = true;
croppedImageHolder.texture = croppedImage;
Vector2 size = croppedImageHolder.rectTransform.sizeDelta;
if( croppedImage.height <= croppedImage.width )
size = new Vector2( 400f, 400f * ( croppedImage.height / (float) croppedImage.width ) );
else
size = new Vector2( 400f * ( croppedImage.width / (float) croppedImage.height ), 400f );
croppedImageHolder.rectTransform.sizeDelta = size;
croppedImageSize.enabled = true;
croppedImageSize.text = "Image size: " + croppedImage.width + ", " + croppedImage.height;
}
else
{
croppedImageHolder.enabled = false;
croppedImageSize.enabled = false;
}
// Destroy the screenshot as we no longer need it in this case
Destroy( screenshot );
},
settings: new ImageCropper.Settings()
{
ovalSelection = ovalSelection,
autoZoomEnabled = autoZoom,
imageBackground = Color.clear, // transparent background
selectionMinAspectRatio = minAspectRatio,
selectionMaxAspectRatio = maxAspectRatio
},
croppedImageResizePolicy: ( ref int width, ref int height ) =>
{
// uncomment lines below to save cropped image at half resolution
//width /= 2;
//height /= 2;
} );
}
}
}