@sdcx/image-crop 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 http://www.sdcx.tech
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # ImageCropView
2
+
3
+ `ImageCropView` 是一个 React Native 原生 UI 组件,用于头像裁剪以及图片裁剪,同时支持图像主体识别后设置需要裁剪的主体区域。
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ yarn add @sdcx/image-crop
9
+ # &
10
+ pod install
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```
16
+ <ImageCropView
17
+ style={'your style'}
18
+ fileUri={'your file uri'}
19
+ cropStyle={'circular' | 'default'}
20
+ onCropped={(uri: string) => {}}
21
+ objectRect={objectRect}
22
+ />
23
+ ```
24
+ #### cropStyle
25
+ 默认default为裁剪矩形,若需要裁剪圆形头像,则设为circular;
26
+
27
+ #### objectRect
28
+ objectRect可设置默认的图片裁剪区域,且当cropStyle为default时有效。
29
+
30
+ objectRect的四个属性分别是(单位都是像素px):
31
+ 1. left: 裁剪区域离图片左边的距离;
32
+ 2. top: 裁剪区域离图片上边的距离;
33
+ 3. width: 裁剪区域的宽度;
34
+ 4. height: 裁剪区域的高度;
35
+
@@ -0,0 +1,19 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "RNImageCrop"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+
10
+ s.homepage = package["homepage"]
11
+ s.license = package["license"]
12
+ s.authors = package["author"]
13
+ s.platforms = { :ios => "10.0" }
14
+ s.source = { :git => "https://github.com/github-account/image-crop.git", :tag => "#{s.version}" }
15
+
16
+ s.source_files = "ios/ImageCrop/**/*.{h,m,mm}"
17
+ s.dependency "React-Core"
18
+ s.dependency "TOCropViewController"
19
+ end
@@ -0,0 +1,36 @@
1
+ // android/build.gradle
2
+
3
+ def safeExtGet(prop, fallback) {
4
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
5
+ }
6
+
7
+ apply plugin: 'com.android.library'
8
+
9
+ android {
10
+ compileOptions {
11
+ sourceCompatibility JavaVersion.VERSION_1_8
12
+ targetCompatibility JavaVersion.VERSION_1_8
13
+ }
14
+
15
+ compileSdkVersion safeExtGet('compileSdkVersion', 30)
16
+ buildToolsVersion safeExtGet('buildToolsVersion', '30.0.2')
17
+
18
+ defaultConfig {
19
+ minSdkVersion safeExtGet('minSdkVersion', 21)
20
+ targetSdkVersion safeExtGet('targetSdkVersion', 30)
21
+ versionCode 1
22
+ versionName "1.0.0"
23
+ }
24
+
25
+ buildTypes {
26
+ release {
27
+ consumerProguardFiles 'proguard-rules.pro'
28
+ }
29
+ }
30
+ }
31
+
32
+ dependencies {
33
+ implementation fileTree(dir: 'libs', include: ['*.jar'])
34
+ implementation 'com.facebook.react:react-native:+'
35
+ implementation 'com.github.yalantis:ucrop:2.2.6'
36
+ }
@@ -0,0 +1,3 @@
1
+ -dontwarn com.yalantis.ucrop**
2
+ -keep class com.yalantis.ucrop** { *; }
3
+ -keep interface com.yalantis.ucrop** { *; }
@@ -0,0 +1,4 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2
+ package="com.reactnative.imagecrop">
3
+
4
+ </manifest>
@@ -0,0 +1,26 @@
1
+ package com.reactnative.imagecrop;
2
+
3
+ import androidx.annotation.NonNull;
4
+
5
+ import java.util.Arrays;
6
+ import java.util.Collections;
7
+ import java.util.List;
8
+
9
+ import com.facebook.react.ReactPackage;
10
+ import com.facebook.react.bridge.NativeModule;
11
+ import com.facebook.react.bridge.ReactApplicationContext;
12
+ import com.facebook.react.uimanager.ViewManager;
13
+
14
+ public class ImageCropPackage implements ReactPackage {
15
+ @NonNull
16
+ @Override
17
+ public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactContext) {
18
+ return Collections.emptyList();
19
+ }
20
+
21
+ @NonNull
22
+ @Override
23
+ public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactContext) {
24
+ return Arrays.asList(new RNImageCropViewManager());
25
+ }
26
+ }
@@ -0,0 +1,70 @@
1
+ package com.reactnative.imagecrop;
2
+
3
+ import com.facebook.react.bridge.ReadableMap;
4
+
5
+ public class ObjectRect {
6
+ private int top;
7
+ private int left;
8
+ private int width;
9
+ private int height;
10
+
11
+ public ObjectRect(int top, int left, int width, int height) {
12
+ this.top = top;
13
+ this.left = left;
14
+ this.width = width;
15
+ this.height = height;
16
+ }
17
+
18
+ public static ObjectRect fromReadableMap(ReadableMap map) {
19
+ int top = -1, left = -1, width = -1, height = -1;
20
+ if (map.hasKey("top")) {
21
+ top = map.getInt("top");
22
+ }
23
+ if (map.hasKey("left")) {
24
+ left = map.getInt("left");
25
+ }
26
+ if (map.hasKey("width")) {
27
+ width = map.getInt("width");
28
+ }
29
+ if (map.hasKey("height")) {
30
+ height = map.getInt("height");
31
+ }
32
+
33
+ if (top != -1 && left != -1 && width != -1 && height != -1) {
34
+ return new ObjectRect(top, left, width, height);
35
+ }
36
+ return null;
37
+ }
38
+
39
+ public int getTop() {
40
+ return top;
41
+ }
42
+
43
+ public void setTop(int top) {
44
+ this.top = top;
45
+ }
46
+
47
+ public int getLeft() {
48
+ return left;
49
+ }
50
+
51
+ public void setLeft(int left) {
52
+ this.left = left;
53
+ }
54
+
55
+ public int getWidth() {
56
+ return width;
57
+ }
58
+
59
+ public void setWidth(int width) {
60
+ this.width = width;
61
+ }
62
+
63
+ public int getHeight() {
64
+ return height;
65
+ }
66
+
67
+ public void setHeight(int height) {
68
+ this.height = height;
69
+ }
70
+ }
@@ -0,0 +1,214 @@
1
+ package com.reactnative.imagecrop;
2
+
3
+ import android.content.Context;
4
+ import android.graphics.Bitmap;
5
+ import android.graphics.BitmapFactory;
6
+ import android.graphics.Color;
7
+ import android.media.ExifInterface;
8
+ import android.net.Uri;
9
+ import android.view.LayoutInflater;
10
+ import android.view.View;
11
+ import android.widget.FrameLayout;
12
+
13
+ import androidx.annotation.NonNull;
14
+
15
+ import com.facebook.common.logging.FLog;
16
+ import com.facebook.react.bridge.Arguments;
17
+ import com.facebook.react.bridge.ReactContext;
18
+ import com.facebook.react.bridge.ReadableMap;
19
+ import com.facebook.react.bridge.WritableMap;
20
+ import com.facebook.react.uimanager.events.RCTEventEmitter;
21
+ import com.yalantis.ucrop.callback.BitmapCropCallback;
22
+ import com.yalantis.ucrop.callback.OverlayViewChangeListener;
23
+ import com.yalantis.ucrop.view.GestureCropImageView;
24
+ import com.yalantis.ucrop.view.OverlayView;
25
+ import com.yalantis.ucrop.view.UCropView;
26
+
27
+ import java.io.File;
28
+ import java.lang.reflect.Field;
29
+ import java.lang.reflect.Method;
30
+ import java.util.UUID;
31
+
32
+ public class RNImageCropView extends FrameLayout {
33
+ private static final int DEFAULT_COMPRESS_QUALITY = 90;
34
+ private static final Bitmap.CompressFormat DEFAULT_COMPRESS_FORMAT = Bitmap.CompressFormat.PNG;
35
+
36
+ private static final String TAG = "RNImageCropView";
37
+ private String fileUri;
38
+ private Uri mOutputUri;
39
+
40
+ public void setFileUri(String fileUri) {
41
+ FLog.i(TAG, "设置属性fileUri = " + fileUri);
42
+ this.fileUri = fileUri;
43
+ }
44
+
45
+ private String cropStyle;
46
+
47
+ public void setCropStyle(String cropStyle) {
48
+ this.cropStyle = cropStyle;
49
+ FLog.i(TAG, "设置属性cropStyle = " + cropStyle);
50
+ }
51
+
52
+ private ObjectRect objectRect;
53
+
54
+ public void setObjectRect(ReadableMap map) {
55
+ FLog.i(TAG, "设置属性objectRect = " + map);
56
+ this.objectRect = ObjectRect.fromReadableMap(map);
57
+ }
58
+
59
+ public void initProperties() {
60
+ try {
61
+ mGestureCropImageView.setImageURI(Uri.parse(fileUri));
62
+ mGestureCropImageView.setImageUri(Uri.parse(fileUri), mOutputUri);
63
+ } catch (Exception e) {
64
+ FLog.i(TAG, "设置初始图片失败:" + e.getMessage());
65
+ }
66
+
67
+ try {
68
+ mGestureCropImageView.setBackgroundColor(Color.BLACK);
69
+ mGestureCropImageView.setRotateEnabled(false);
70
+
71
+ if (cropStyle != null && cropStyle.equals("circular")) {
72
+ mOverlayView.setShowCropGrid(false);
73
+ mOverlayView.setCircleDimmedLayer(true);
74
+ mOverlayView.setShowCropFrame(false);
75
+ mGestureCropImageView.setTargetAspectRatio(1f);
76
+ } else {
77
+ mOverlayView.setFreestyleCropMode(OverlayView.FREESTYLE_CROP_MODE_ENABLE);
78
+ if (objectRect != null) {
79
+ //设置图像主体边框
80
+ BitmapFactory.Options options = new BitmapFactory.Options();
81
+ options.inJustDecodeBounds = true;
82
+ File file = new File(fileUri.replace("file:///", "/"));
83
+ BitmapFactory.decodeFile(file.getAbsolutePath(), options);
84
+ int imageHeight = options.outHeight;
85
+ int imageWidth = options.outWidth;
86
+
87
+ //如果发现图片存在旋转,需要调转图片宽高
88
+ int degree = getBitmapDegree(file);
89
+ if (degree == 90 || degree == 270) {
90
+ FLog.i(TAG, "需要调转图片宽高");
91
+ int tmp = imageWidth;
92
+ imageWidth = imageHeight;
93
+ imageHeight = tmp;
94
+ }
95
+
96
+ FLog.i(TAG, "imageHeight :" + imageHeight);
97
+ FLog.i(TAG, "imageWidth :" + imageWidth);
98
+ setupDetectedObjectBounds(imageWidth, imageHeight, objectRect.getTop(), objectRect.getLeft(), objectRect.getWidth(), objectRect.getHeight());
99
+ } else {
100
+ mGestureCropImageView.setTargetAspectRatio(1f);
101
+ }
102
+ }
103
+ } catch (Exception e) {
104
+ FLog.i(TAG, "初始化相关属性失败:" + e.getMessage());
105
+ }
106
+ }
107
+
108
+ private void setupDetectedObjectBounds(float imageWidth, float imageHeight, float top, float left, float width, float height) {
109
+ postDelayed(new Runnable() {
110
+ @Override
111
+ public void run() {
112
+ try {
113
+ Field mTargetAspectRatioField = OverlayView.class.getDeclaredField("mTargetAspectRatio");
114
+ mTargetAspectRatioField.setAccessible(true);
115
+ float mTargetAspectRatio = mTargetAspectRatioField.getFloat(mOverlayView);
116
+ Field mThisHeightField = OverlayView.class.getDeclaredField("mThisHeight");
117
+ mThisHeightField.setAccessible(true);
118
+ int mThisHeight = mThisHeightField.getInt(mOverlayView);
119
+ Field mThisWidthField = OverlayView.class.getDeclaredField("mThisWidth");
120
+ mThisWidthField.setAccessible(true);
121
+ int mThisWidth = mThisWidthField.getInt(mOverlayView);
122
+
123
+ int halfDiff = (mThisHeight - (int) (mThisWidth / mTargetAspectRatio)) / 2;
124
+ float mLeft = mOverlayView.getPaddingLeft() + mThisWidth * (left / imageWidth);
125
+ float mTop = mOverlayView.getPaddingTop() + halfDiff + (mThisWidth / mTargetAspectRatio) * top / imageHeight;
126
+ float mRight = mLeft + mThisWidth * width / imageWidth;
127
+ float mBottom = mTop + mThisWidth / mTargetAspectRatio * height / imageHeight;
128
+ mOverlayView.getCropViewRect().set(mLeft, mTop, mRight, mBottom);
129
+
130
+ OverlayViewChangeListener overlayViewChangeListener = mOverlayView.getOverlayViewChangeListener();
131
+ if (overlayViewChangeListener != null) {
132
+ overlayViewChangeListener.onCropRectUpdated(mOverlayView.getCropViewRect());
133
+ }
134
+
135
+ Method updateGridPointsMethod = OverlayView.class.getDeclaredMethod("updateGridPoints");
136
+ updateGridPointsMethod.setAccessible(true);
137
+ updateGridPointsMethod.invoke(mOverlayView);
138
+ mOverlayView.postInvalidate();
139
+
140
+ } catch (Exception e) {
141
+ FLog.e(TAG, "setupDetectedObjectBounds on Error: " + e.getMessage());
142
+ }
143
+ }
144
+ }, 10);
145
+ }
146
+ private UCropView mUCropView;
147
+ private GestureCropImageView mGestureCropImageView;
148
+ private OverlayView mOverlayView;
149
+
150
+ public RNImageCropView(Context context) {
151
+ super(context);
152
+ init(context);
153
+ }
154
+
155
+ private void init(Context context) {
156
+ View view = LayoutInflater.from(context).inflate(R.layout.rn_crop_view, this, true);
157
+ mUCropView = view.findViewById(R.id.ucrop);
158
+ mGestureCropImageView = mUCropView.getCropImageView();
159
+ mOverlayView = mUCropView.getOverlayView();
160
+
161
+ mOutputUri = Uri.fromFile(new File(context.getCacheDir(), UUID.randomUUID().toString() + ".png"));
162
+ FLog.i(TAG, "裁剪后将保存为 = " + mOutputUri.toString());
163
+ }
164
+
165
+ public void crop() {
166
+ mGestureCropImageView.cropAndSaveImage(DEFAULT_COMPRESS_FORMAT, DEFAULT_COMPRESS_QUALITY, new BitmapCropCallback() {
167
+ @Override
168
+ public void onBitmapCropped(@NonNull Uri resultUri, int offsetX, int offsetY, int imageWidth, int imageHeight) {
169
+ FLog.i(TAG, "裁剪后已保存为 = " + resultUri.toString());
170
+ onCropped(resultUri.toString());
171
+ }
172
+
173
+ @Override
174
+ public void onCropFailure(@NonNull Throwable t) {
175
+ FLog.i(TAG, "保存失败 = " + t.toString());
176
+ }
177
+ });
178
+ }
179
+
180
+ private void onCropped(String uri) {
181
+ WritableMap data = Arguments.createMap();
182
+ data.putString("uri", uri);
183
+ ReactContext reactContext = (ReactContext) getContext();
184
+ reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
185
+ getId(),
186
+ "onCropped",
187
+ data);
188
+ }
189
+
190
+ private int getBitmapDegree(File file) {
191
+ int degree = 0;
192
+ try {
193
+ // 从指定路径下读取图片,并获取其EXIF信息
194
+ ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath());
195
+ // 获取图片的旋转信息
196
+ int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
197
+ ExifInterface.ORIENTATION_NORMAL);
198
+ switch (orientation) {
199
+ case ExifInterface.ORIENTATION_ROTATE_90:
200
+ degree = 90;
201
+ break;
202
+ case ExifInterface.ORIENTATION_ROTATE_180:
203
+ degree = 180;
204
+ break;
205
+ case ExifInterface.ORIENTATION_ROTATE_270:
206
+ degree = 270;
207
+ break;
208
+ }
209
+ } catch (Exception e) {
210
+ e.printStackTrace();
211
+ }
212
+ return degree;
213
+ }
214
+ }
@@ -0,0 +1,77 @@
1
+ package com.reactnative.imagecrop;
2
+
3
+ import androidx.annotation.NonNull;
4
+ import androidx.annotation.Nullable;
5
+
6
+ import com.facebook.react.bridge.ReadableArray;
7
+ import com.facebook.react.bridge.ReadableMap;
8
+ import com.facebook.react.common.MapBuilder;
9
+ import com.facebook.react.uimanager.ThemedReactContext;
10
+ import com.facebook.react.uimanager.ViewGroupManager;
11
+ import com.facebook.react.uimanager.annotations.ReactProp;
12
+
13
+ import java.util.Map;
14
+
15
+ public class RNImageCropViewManager extends ViewGroupManager<RNImageCropView> {
16
+ private static final String REACT_CLASS = "RNImageCrop";
17
+
18
+ private static final int COMMAND_CROP = 1;
19
+
20
+ @NonNull
21
+ @Override
22
+ public String getName() {
23
+ return REACT_CLASS;
24
+ }
25
+
26
+ @NonNull
27
+ @Override
28
+ protected RNImageCropView createViewInstance(@NonNull ThemedReactContext reactContext) {
29
+ return new RNImageCropView(reactContext);
30
+ }
31
+
32
+ @ReactProp(name = "fileUri")
33
+ public void setFileUri(RNImageCropView RNImageCropView, String fileUri) {
34
+ RNImageCropView.setFileUri(fileUri);
35
+ }
36
+
37
+ @ReactProp(name = "cropStyle")
38
+ public void setCropStyle(RNImageCropView RNImageCropView, String cropStyle) {
39
+ RNImageCropView.setCropStyle(cropStyle);
40
+ }
41
+
42
+ @ReactProp(name = "objectRect")
43
+ public void setObjectRect(RNImageCropView RNImageCropView, ReadableMap objectRect) {
44
+ RNImageCropView.setObjectRect(objectRect);
45
+ }
46
+
47
+ @Override
48
+ protected void onAfterUpdateTransaction(@NonNull RNImageCropView RNImageCropView) {
49
+ super.onAfterUpdateTransaction(RNImageCropView);
50
+ RNImageCropView.initProperties();
51
+ }
52
+
53
+ @Nullable
54
+ @Override
55
+ public Map<String, Integer> getCommandsMap() {
56
+ return MapBuilder.of("crop", COMMAND_CROP);
57
+ }
58
+
59
+ @Override
60
+ public void receiveCommand(@NonNull RNImageCropView root, String commandId, @Nullable ReadableArray args) {
61
+ super.receiveCommand(root, commandId, args);
62
+ int commandIdInt = Integer.parseInt(commandId);
63
+ switch (commandIdInt) {
64
+ case COMMAND_CROP:
65
+ root.crop();
66
+ break;
67
+ }
68
+ }
69
+
70
+ public Map<String, Object> getExportedCustomBubblingEventTypeConstants() {
71
+ String name = "phasedRegistrationNames";
72
+ String bubbled = "bubbled";
73
+ return MapBuilder.<String, Object>builder()
74
+ .put("onCropped", MapBuilder.of(name, MapBuilder.of(bubbled, "onCropped")))
75
+ .build();
76
+ }
77
+ }
@@ -0,0 +1,7 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <com.yalantis.ucrop.view.UCropView xmlns:android="http://schemas.android.com/apk/res/android"
3
+ android:id="@+id/ucrop"
4
+ android:layout_width="match_parent"
5
+ android:layout_height="match_parent">
6
+
7
+ </com.yalantis.ucrop.view.UCropView>
@@ -0,0 +1,30 @@
1
+ #import <UIKit/UIKit.h>
2
+ #import <React/UIView+React.h>
3
+
4
+ #import "TOCropView.h"
5
+
6
+ @interface RNImageCrop : UIView
7
+
8
+ /**
9
+ RN传递进来的属性值:需要裁剪图片路径
10
+ */
11
+ @property(nonatomic, copy, nonnull) NSString *fileUri;
12
+
13
+ /**
14
+ RN传递进来的属性值:裁剪样式,default | circular
15
+ */
16
+ @property(nonatomic, copy, nullable) NSString *cropStyle;
17
+
18
+ /**
19
+ RN传递进来的属性值:图像主体Rect,如{"width":208,"left":43,"top":111,"height":354}
20
+ */
21
+ @property(nonatomic, copy, nullable) id objectRect;
22
+
23
+ /**
24
+ 选定图片区域后,确认裁剪操作
25
+ */
26
+ - (void)crop;
27
+
28
+ @property(nonatomic, copy, nullable) RCTBubblingEventBlock onCropped;
29
+
30
+ @end
@@ -0,0 +1,129 @@
1
+ #import "RNImageCrop.h"
2
+ #import "UIImage+CropRotate.h"
3
+
4
+ @interface RNImageCrop()
5
+
6
+ /**
7
+ The original, uncropped image that was passed to this controller.
8
+ */
9
+ @property (nonatomic, nonnull) UIImage *image;
10
+
11
+ /**
12
+ The cropping style of this particular crop view controller
13
+ */
14
+ @property (nonatomic) TOCropViewCroppingStyle croppingStyle;
15
+
16
+ /**
17
+ The crop view managed by this view controller.
18
+ */
19
+ @property (nonatomic, strong, nonnull) TOCropView *cropView;
20
+
21
+ @property (nonatomic, assign) BOOL initialSetupPerformed;
22
+
23
+ @end
24
+
25
+ @implementation RNImageCrop
26
+
27
+ - (instancetype)initWithFrame:(CGRect)frame {
28
+ if ((self = [super initWithFrame:frame])) {
29
+ }
30
+ return self;
31
+ }
32
+
33
+ - (void)layoutSubviews {
34
+ [super layoutSubviews];
35
+ if (self.cropView && [self.subviews containsObject:self.cropView]) {
36
+ if (self.initialSetupPerformed) {
37
+ return;
38
+ }
39
+ self.initialSetupPerformed = YES;
40
+
41
+ //设置图片主体检测参数
42
+ if (![_cropStyle isEqualToString:@"circular"]
43
+ && _objectRect != nil
44
+ && [_objectRect objectForKey:@"top"]
45
+ && [_objectRect objectForKey:@"left"]
46
+ && [_objectRect objectForKey:@"width"]
47
+ && [_objectRect objectForKey:@"height"]) {
48
+ int top = [[_objectRect valueForKey:@"top"] intValue];
49
+ int left = [[_objectRect valueForKey:@"left"] intValue];
50
+ int width = [[_objectRect valueForKey:@"width"] intValue];
51
+ int height = [[_objectRect valueForKey:@"height"] intValue];
52
+ [self.cropView setImageCropFrame:CGRectMake(left, top, width, height)];
53
+ }
54
+
55
+ //存在极小的概率,初始化时只在左上角展示一小块图片区域,目前没有找到较好的方案,尝试延迟一点时间初始化CropView可以解决问题
56
+ // [self.cropView performInitialSetup];
57
+ [self.cropView performSelector:@selector(performInitialSetup) withObject:nil afterDelay:0.05];
58
+ }
59
+ }
60
+
61
+ - (void)setFileUri:(NSString *)fileUri {
62
+ _fileUri = fileUri;
63
+ _image = [UIImage imageWithContentsOfFile: [[NSURL alloc] initWithString:fileUri].path];
64
+ }
65
+
66
+ - (void)didSetProps:(NSArray<NSString *> *)changedProps {
67
+ [self addCropView:self.croppingStyle image:self.image];
68
+ }
69
+
70
+ - (void)addCropView:(TOCropViewCroppingStyle)style image:(UIImage *)image {
71
+ if (!_cropView) {
72
+ _cropView = [[TOCropView alloc] initWithCroppingStyle:style image:image];
73
+ _cropView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
74
+ [_cropView setBackgroundColor:[UIColor blackColor]];
75
+ }
76
+
77
+ if (![self.subviews containsObject:self.cropView]) {
78
+ [self addSubview:_cropView];
79
+ }
80
+ }
81
+
82
+ - (void)crop {
83
+ CGRect cropFrame = self.cropView.imageCropFrame;
84
+ NSInteger angle = self.cropView.angle;
85
+
86
+ UIImage *image = nil;
87
+ if (angle == 0 && CGRectEqualToRect(cropFrame, (CGRect){CGPointZero, self.image.size})) {
88
+ image = self.image;
89
+ } else {
90
+ image = [self.image croppedImageWithFrame:cropFrame angle:angle circularClip:NO];
91
+ }
92
+
93
+ [self saveImage:image];
94
+ }
95
+
96
+ - (void)saveImage:(UIImage*)image {
97
+ NSString *fileName = [NSString stringWithFormat:@"%@.png", [self produceUUID]];
98
+ NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
99
+ BOOL result =[UIImagePNGRepresentation(image)writeToFile:filePath atomically:YES];
100
+
101
+ if(result ==YES) {
102
+ NSLog(@"保存成功: %@", filePath);
103
+
104
+ if (self.onCropped) {
105
+ self.onCropped(@{
106
+ @"uri": [[NSURL alloc] initFileURLWithPath:filePath].absoluteString
107
+ });
108
+ }
109
+ }
110
+ }
111
+
112
+ - (TOCropViewCroppingStyle)croppingStyle {
113
+ if (_cropStyle && [_cropStyle isEqualToString:@"circular"]) {
114
+ return TOCropViewCroppingStyleCircular;
115
+ }
116
+ return TOCropViewCroppingStyleDefault;
117
+ }
118
+
119
+
120
+ - (NSString *)produceUUID {
121
+ CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
122
+ CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
123
+ NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
124
+ CFRelease(uuid_ref);
125
+ CFRelease(uuid_string_ref);
126
+ return [uuid uppercaseString];
127
+ }
128
+
129
+ @end
@@ -0,0 +1,18 @@
1
+ //
2
+ // RNImageCropManager.h
3
+ // RNImageCrop
4
+ //
5
+ // Created by vibe on 2023/4/28.
6
+ //
7
+
8
+ #import <React/RCTViewManager.h>
9
+ #import <React/RCTBridgeModule.h>
10
+ #import <React/RCTUIManager.h>
11
+
12
+ NS_ASSUME_NONNULL_BEGIN
13
+
14
+ @interface RNImageCropManager : RCTViewManager
15
+
16
+ @end
17
+
18
+ NS_ASSUME_NONNULL_END
@@ -0,0 +1,37 @@
1
+ //
2
+ // RNCropManager.m
3
+ // RNCrop
4
+ //
5
+ // Created by vibe on 2022/2/8.
6
+ //
7
+
8
+ #import "RNImageCropManager.h"
9
+ #import "RNImageCrop.h"
10
+
11
+ @implementation RNImageCropManager
12
+
13
+ RCT_EXPORT_MODULE(RNImageCrop)
14
+ RCT_EXPORT_VIEW_PROPERTY(fileUri, NSString)
15
+ RCT_EXPORT_VIEW_PROPERTY(cropStyle, NSString)
16
+ RCT_EXPORT_VIEW_PROPERTY(objectRect, id)
17
+ RCT_EXPORT_VIEW_PROPERTY(onCropped, RCTBubblingEventBlock)
18
+ RCT_EXPORT_METHOD(crop:(nonnull NSNumber *)reactTag) {
19
+ [self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *,UIView *> *viewRegistry) {
20
+ RNImageCrop *rnCrop = viewRegistry[reactTag];
21
+ if (![rnCrop isKindOfClass:[RNImageCrop class]]) {
22
+ RCTLogError(@"Invalid view returned from registry, expecting RNCrop, got: %@", rnCrop);
23
+ } else {
24
+ dispatch_async(dispatch_get_main_queue(), ^{
25
+ RNImageCrop *rnCrop = (RNImageCrop *)viewRegistry[reactTag];
26
+ [rnCrop crop];
27
+ });
28
+ }
29
+ }];
30
+ }
31
+
32
+ - (UIView *)view
33
+ {
34
+ return [RNImageCrop new];
35
+ }
36
+
37
+ @end
@@ -0,0 +1,283 @@
1
+ // !$*UTF8*$!
2
+ {
3
+ archiveVersion = 1;
4
+ classes = {
5
+ };
6
+ objectVersion = 48;
7
+ objects = {
8
+
9
+ /* Begin PBXBuildFile section */
10
+ 91C884A6202C3E8600EC0A20 /* undefined.m in Sources */ = {isa = PBXBuildFile; fileRef = 91C884A1202C3E8600EC0A20 /* undefined.m */; };
11
+ /* End PBXBuildFile section */
12
+
13
+ /* Begin PBXCopyFilesBuildPhase section */
14
+ 910362D01FE9318600F4DA8E /* CopyFiles */ = {
15
+ isa = PBXCopyFilesBuildPhase;
16
+ buildActionMask = 2147483647;
17
+ dstPath = "include/$(PRODUCT_NAME)";
18
+ dstSubfolderSpec = 16;
19
+ files = (
20
+ );
21
+ runOnlyForDeploymentPostprocessing = 0;
22
+ };
23
+ /* End PBXCopyFilesBuildPhase section */
24
+
25
+ /* Begin PBXFileReference section */
26
+ 910362D21FE9318600F4DA8E /* libImageCrop.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libImageCrop.a; sourceTree = BUILT_PRODUCTS_DIR; };
27
+ 91C884A1202C3E8600EC0A20 /* undefined.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = undefined.m; sourceTree = "<group>"; };
28
+ 91C884A2202C3E8600EC0A20 /* undefined.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = undefined.h; sourceTree = "<group>"; };
29
+ /* End PBXFileReference section */
30
+
31
+ /* Begin PBXFrameworksBuildPhase section */
32
+ 910362CF1FE9318600F4DA8E /* Frameworks */ = {
33
+ isa = PBXFrameworksBuildPhase;
34
+ buildActionMask = 2147483647;
35
+ files = (
36
+ );
37
+ runOnlyForDeploymentPostprocessing = 0;
38
+ };
39
+ /* End PBXFrameworksBuildPhase section */
40
+
41
+ /* Begin PBXGroup section */
42
+ 910362C91FE9318600F4DA8E = {
43
+ isa = PBXGroup;
44
+ children = (
45
+ 910362D41FE9318600F4DA8E /* ImageCrop */,
46
+ 910362D31FE9318600F4DA8E /* Products */,
47
+ );
48
+ sourceTree = "<group>";
49
+ };
50
+ 910362D31FE9318600F4DA8E /* Products */ = {
51
+ isa = PBXGroup;
52
+ children = (
53
+ 910362D21FE9318600F4DA8E /* libImageCrop.a */,
54
+ );
55
+ name = Products;
56
+ sourceTree = "<group>";
57
+ };
58
+ 910362D41FE9318600F4DA8E /* ImageCrop */ = {
59
+ isa = PBXGroup;
60
+ children = (
61
+ 91C884A2202C3E8600EC0A20 /* undefined.h */,
62
+ 91C884A1202C3E8600EC0A20 /* undefined.m */,
63
+ );
64
+ path = ImageCrop;
65
+ sourceTree = "<group>";
66
+ };
67
+ /* End PBXGroup section */
68
+
69
+ /* Begin PBXNativeTarget section */
70
+ 910362D11FE9318600F4DA8E /* ImageCrop */ = {
71
+ isa = PBXNativeTarget;
72
+ buildConfigurationList = 910362DB1FE9318600F4DA8E /* Build configuration list for PBXNativeTarget "ImageCrop" */;
73
+ buildPhases = (
74
+ 910362CE1FE9318600F4DA8E /* Sources */,
75
+ 910362CF1FE9318600F4DA8E /* Frameworks */,
76
+ 910362D01FE9318600F4DA8E /* CopyFiles */,
77
+ );
78
+ buildRules = (
79
+ );
80
+ dependencies = (
81
+ );
82
+ name = ImageCrop;
83
+ productName = ImageCrop;
84
+ productReference = 910362D21FE9318600F4DA8E /* libImageCrop.a */;
85
+ productType = "com.apple.product-type.library.static";
86
+ };
87
+ /* End PBXNativeTarget section */
88
+
89
+ /* Begin PBXProject section */
90
+ 910362CA1FE9318600F4DA8E /* Project object */ = {
91
+ isa = PBXProject;
92
+ attributes = {
93
+ LastUpgradeCheck = 0920;
94
+ ORGANIZATIONNAME = Listen;
95
+ TargetAttributes = {
96
+ 910362D11FE9318600F4DA8E = {
97
+ CreatedOnToolsVersion = 9.2;
98
+ ProvisioningStyle = Automatic;
99
+ };
100
+ };
101
+ };
102
+ buildConfigurationList = 910362CD1FE9318600F4DA8E /* Build configuration list for PBXProject "ImageCrop" */;
103
+ compatibilityVersion = "Xcode 8.0";
104
+ developmentRegion = en;
105
+ hasScannedForEncodings = 0;
106
+ knownRegions = (
107
+ en,
108
+ );
109
+ mainGroup = 910362C91FE9318600F4DA8E;
110
+ productRefGroup = 910362D31FE9318600F4DA8E /* Products */;
111
+ projectDirPath = "";
112
+ projectRoot = "";
113
+ targets = (
114
+ 910362D11FE9318600F4DA8E /* ImageCrop */,
115
+ );
116
+ };
117
+ /* End PBXProject section */
118
+
119
+ /* Begin PBXSourcesBuildPhase section */
120
+ 910362CE1FE9318600F4DA8E /* Sources */ = {
121
+ isa = PBXSourcesBuildPhase;
122
+ buildActionMask = 2147483647;
123
+ files = (
124
+ 91C884A6202C3E8600EC0A20 /* undefined.m in Sources */,
125
+ );
126
+ runOnlyForDeploymentPostprocessing = 0;
127
+ };
128
+ /* End PBXSourcesBuildPhase section */
129
+
130
+ /* Begin XCBuildConfiguration section */
131
+ 910362D91FE9318600F4DA8E /* Debug */ = {
132
+ isa = XCBuildConfiguration;
133
+ buildSettings = {
134
+ ALWAYS_SEARCH_USER_PATHS = NO;
135
+ CLANG_ANALYZER_NONNULL = YES;
136
+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
137
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
138
+ CLANG_CXX_LIBRARY = "libc++";
139
+ CLANG_ENABLE_MODULES = YES;
140
+ CLANG_ENABLE_OBJC_ARC = YES;
141
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
142
+ CLANG_WARN_BOOL_CONVERSION = YES;
143
+ CLANG_WARN_COMMA = YES;
144
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
145
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
146
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
147
+ CLANG_WARN_EMPTY_BODY = YES;
148
+ CLANG_WARN_ENUM_CONVERSION = YES;
149
+ CLANG_WARN_INFINITE_RECURSION = YES;
150
+ CLANG_WARN_INT_CONVERSION = YES;
151
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
152
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
153
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
154
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
155
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
156
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
157
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
158
+ CLANG_WARN_UNREACHABLE_CODE = YES;
159
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
160
+ CODE_SIGN_IDENTITY = "iPhone Developer";
161
+ COPY_PHASE_STRIP = NO;
162
+ DEBUG_INFORMATION_FORMAT = dwarf;
163
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
164
+ ENABLE_TESTABILITY = YES;
165
+ GCC_C_LANGUAGE_STANDARD = gnu11;
166
+ GCC_DYNAMIC_NO_PIC = NO;
167
+ GCC_NO_COMMON_BLOCKS = YES;
168
+ GCC_OPTIMIZATION_LEVEL = 0;
169
+ GCC_PREPROCESSOR_DEFINITIONS = (
170
+ "DEBUG=1",
171
+ "$(inherited)",
172
+ );
173
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
174
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
175
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
176
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
177
+ GCC_WARN_UNUSED_FUNCTION = YES;
178
+ GCC_WARN_UNUSED_VARIABLE = YES;
179
+ IPHONEOS_DEPLOYMENT_TARGET = 7.0;
180
+ MTL_ENABLE_DEBUG_INFO = YES;
181
+ ONLY_ACTIVE_ARCH = YES;
182
+ SDKROOT = iphoneos;
183
+ };
184
+ name = Debug;
185
+ };
186
+ 910362DA1FE9318600F4DA8E /* Release */ = {
187
+ isa = XCBuildConfiguration;
188
+ buildSettings = {
189
+ ALWAYS_SEARCH_USER_PATHS = NO;
190
+ CLANG_ANALYZER_NONNULL = YES;
191
+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
192
+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
193
+ CLANG_CXX_LIBRARY = "libc++";
194
+ CLANG_ENABLE_MODULES = YES;
195
+ CLANG_ENABLE_OBJC_ARC = YES;
196
+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
197
+ CLANG_WARN_BOOL_CONVERSION = YES;
198
+ CLANG_WARN_COMMA = YES;
199
+ CLANG_WARN_CONSTANT_CONVERSION = YES;
200
+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
201
+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
202
+ CLANG_WARN_EMPTY_BODY = YES;
203
+ CLANG_WARN_ENUM_CONVERSION = YES;
204
+ CLANG_WARN_INFINITE_RECURSION = YES;
205
+ CLANG_WARN_INT_CONVERSION = YES;
206
+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
207
+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
208
+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
209
+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
210
+ CLANG_WARN_STRICT_PROTOTYPES = YES;
211
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
212
+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
213
+ CLANG_WARN_UNREACHABLE_CODE = YES;
214
+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
215
+ CODE_SIGN_IDENTITY = "iPhone Developer";
216
+ COPY_PHASE_STRIP = NO;
217
+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
218
+ ENABLE_NS_ASSERTIONS = NO;
219
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
220
+ GCC_C_LANGUAGE_STANDARD = gnu11;
221
+ GCC_NO_COMMON_BLOCKS = YES;
222
+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
223
+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
224
+ GCC_WARN_UNDECLARED_SELECTOR = YES;
225
+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
226
+ GCC_WARN_UNUSED_FUNCTION = YES;
227
+ GCC_WARN_UNUSED_VARIABLE = YES;
228
+ IPHONEOS_DEPLOYMENT_TARGET = 7.0;
229
+ MTL_ENABLE_DEBUG_INFO = NO;
230
+ SDKROOT = iphoneos;
231
+ VALIDATE_PRODUCT = YES;
232
+ };
233
+ name = Release;
234
+ };
235
+ 910362DC1FE9318600F4DA8E /* Debug */ = {
236
+ isa = XCBuildConfiguration;
237
+ buildSettings = {
238
+ CODE_SIGN_STYLE = Automatic;
239
+ DEVELOPMENT_TEAM = 9H9696K6NL;
240
+ OTHER_LDFLAGS = "-ObjC";
241
+ PRODUCT_NAME = "$(TARGET_NAME)";
242
+ SKIP_INSTALL = YES;
243
+ TARGETED_DEVICE_FAMILY = "1,2";
244
+ };
245
+ name = Debug;
246
+ };
247
+ 910362DD1FE9318600F4DA8E /* Release */ = {
248
+ isa = XCBuildConfiguration;
249
+ buildSettings = {
250
+ CODE_SIGN_STYLE = Automatic;
251
+ DEVELOPMENT_TEAM = 9H9696K6NL;
252
+ OTHER_LDFLAGS = "-ObjC";
253
+ PRODUCT_NAME = "$(TARGET_NAME)";
254
+ SKIP_INSTALL = YES;
255
+ TARGETED_DEVICE_FAMILY = "1,2";
256
+ };
257
+ name = Release;
258
+ };
259
+ /* End XCBuildConfiguration section */
260
+
261
+ /* Begin XCConfigurationList section */
262
+ 910362CD1FE9318600F4DA8E /* Build configuration list for PBXProject "ImageCrop" */ = {
263
+ isa = XCConfigurationList;
264
+ buildConfigurations = (
265
+ 910362D91FE9318600F4DA8E /* Debug */,
266
+ 910362DA1FE9318600F4DA8E /* Release */,
267
+ );
268
+ defaultConfigurationIsVisible = 0;
269
+ defaultConfigurationName = Release;
270
+ };
271
+ 910362DB1FE9318600F4DA8E /* Build configuration list for PBXNativeTarget "ImageCrop" */ = {
272
+ isa = XCConfigurationList;
273
+ buildConfigurations = (
274
+ 910362DC1FE9318600F4DA8E /* Debug */,
275
+ 910362DD1FE9318600F4DA8E /* Release */,
276
+ );
277
+ defaultConfigurationIsVisible = 0;
278
+ defaultConfigurationName = Release;
279
+ };
280
+ /* End XCConfigurationList section */
281
+ };
282
+ rootObject = 910362CA1FE9318600F4DA8E /* Project object */;
283
+ }
@@ -0,0 +1,15 @@
1
+ import { ViewProps, ViewStyle } from 'react-native';
2
+ import React from 'react';
3
+ import { ImageCropViewRef } from './ImageCropViewRef';
4
+ import { ObjectRect } from './typings';
5
+ interface SupperProps extends ViewProps {
6
+ fileUri: string;
7
+ objectRect?: ObjectRect;
8
+ cropStyle?: 'circular' | 'default';
9
+ }
10
+ interface CropViewProps extends SupperProps {
11
+ onCropped: (uri: string) => void;
12
+ style: ViewStyle;
13
+ }
14
+ declare const ImageCropView: React.ForwardRefExoticComponent<CropViewProps & React.RefAttributes<ImageCropViewRef>>;
15
+ export default ImageCropView;
@@ -0,0 +1,24 @@
1
+ import { findNodeHandle, Platform, requireNativeComponent, UIManager } from 'react-native';
2
+ import React, { forwardRef, useCallback, useImperativeHandle, useRef } from 'react';
3
+ const CropViewNativeComponent = requireNativeComponent('RNImageCrop');
4
+ const ImageCropView = forwardRef(({ fileUri, cropStyle, objectRect, style, onCropped }, ref) => {
5
+ const reactTag = useRef(null);
6
+ const crop = useCallback(() => {
7
+ UIManager.dispatchViewManagerCommand(reactTag.current, Platform.OS === 'ios'
8
+ ? UIManager.getViewManagerConfig('RNImageCrop').Commands.crop
9
+ : UIManager.getViewManagerConfig('RNImageCrop').Commands.crop.toString(), Platform.OS === 'ios' ? [] : [reactTag.current]);
10
+ }, []);
11
+ const onNativeCropped = useCallback(({ nativeEvent }) => {
12
+ const uri = nativeEvent.uri;
13
+ if (onCropped) {
14
+ onCropped(uri);
15
+ }
16
+ }, [onCropped]);
17
+ useImperativeHandle(ref, () => ({
18
+ crop,
19
+ }), [crop]);
20
+ return (<CropViewNativeComponent fileUri={fileUri} cropStyle={cropStyle} objectRect={objectRect} onCropped={onNativeCropped} style={style} ref={mRef => {
21
+ reactTag.current = findNodeHandle(mRef);
22
+ }}/>);
23
+ });
24
+ export default ImageCropView;
@@ -0,0 +1,3 @@
1
+ export interface ImageCropViewRef {
2
+ crop: () => void;
3
+ }
@@ -0,0 +1 @@
1
+ export {};
package/lib/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import ImageCropView from './ImageCropView';
2
+ import { ImageCropViewRef } from './ImageCropViewRef';
3
+ import { ObjectRect } from './typings';
4
+ export { ImageCropView };
5
+ export type { ImageCropViewRef, ObjectRect };
package/lib/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import ImageCropView from './ImageCropView';
2
+ export { ImageCropView };
@@ -0,0 +1,6 @@
1
+ export interface ObjectRect {
2
+ top: number;
3
+ left: number;
4
+ width: number;
5
+ height: number;
6
+ }
package/lib/typings.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@sdcx/image-crop",
3
+ "description": "A React Native ui component for image crop.",
4
+ "version": "0.1.0",
5
+ "main": "./lib/index.js",
6
+ "typings": "./lib/index.d.ts",
7
+ "react-native": "src/index",
8
+ "nativePackage": true,
9
+ "files": [
10
+ "src",
11
+ "lib",
12
+ "android",
13
+ "ios",
14
+ "RNImageCrop.podspec",
15
+ "!android/build",
16
+ "!ios/build",
17
+ "!**/__tests__"
18
+ ],
19
+ "repository": "https://github.com/sdcxtech/react-native-troika",
20
+ "homepage": "https://github.com/sdcxtech/react-native-troika/tree/master/packages/image-crop#readme",
21
+ "author": "sdcx",
22
+ "license": "MIT",
23
+ "keywords": [
24
+ "react-native",
25
+ "image-crop"
26
+ ],
27
+ "scripts": {
28
+ "build": "rm -rf ./lib && tsc -p tsconfig.build.json",
29
+ "prepare": "npm run build",
30
+ "tsc": "tsc",
31
+ "test": "jest",
32
+ "lint": "eslint . --fix --ext .js,.jsx,.ts,.tsx"
33
+ },
34
+ "peerDependencies": {
35
+ "react": ">=16.8",
36
+ "react-native": ">=0.60"
37
+ },
38
+ "devDependencies": {
39
+ "@babel/core": "^7.13.10",
40
+ "@babel/runtime": "^7.13.10",
41
+ "@react-native-community/eslint-config": "^3.0.0",
42
+ "@types/jest": "^27.0.1",
43
+ "@types/react": "^17.0.2",
44
+ "@types/react-native": "^0.67.0",
45
+ "@types/react-test-renderer": "17.0.2",
46
+ "babel-jest": "^27.0.6",
47
+ "jest": "^27.0.6",
48
+ "metro-react-native-babel-preset": "^0.66.2",
49
+ "react": "17.0.2",
50
+ "react-native": "^0.67.4",
51
+ "react-test-renderer": "17.0.2",
52
+ "eslint": "^7.32.0",
53
+ "typescript": "^4.6.4"
54
+ },
55
+ "jest": {
56
+ "preset": "react-native",
57
+ "moduleFileExtensions": [
58
+ "ts",
59
+ "tsx",
60
+ "js",
61
+ "jsx",
62
+ "json",
63
+ "node"
64
+ ]
65
+ }
66
+ }
@@ -0,0 +1,69 @@
1
+ import { findNodeHandle, Platform, requireNativeComponent, UIManager, ViewProps, ViewStyle } from 'react-native'
2
+ import React, { forwardRef, useCallback, useImperativeHandle, useRef } from 'react'
3
+ import { ImageCropViewRef } from './ImageCropViewRef'
4
+ import { ObjectRect } from './typings'
5
+
6
+ const CropViewNativeComponent = requireNativeComponent<CropViewNativeComponentProps>('RNImageCrop')
7
+
8
+ interface SupperProps extends ViewProps {
9
+ fileUri: string
10
+ objectRect?: ObjectRect
11
+ cropStyle?: 'circular' | 'default'
12
+ }
13
+
14
+ interface CropViewNativeComponentProps extends SupperProps {
15
+ onCropped: (callback: any) => void
16
+ }
17
+
18
+ interface CropViewProps extends SupperProps {
19
+ onCropped: (uri: string) => void
20
+ style: ViewStyle
21
+ }
22
+
23
+ const ImageCropView = forwardRef<ImageCropViewRef, CropViewProps>(
24
+ ({ fileUri, cropStyle, objectRect, style, onCropped }: CropViewProps, ref) => {
25
+ const reactTag = useRef<number | null>(null)
26
+ const crop = useCallback(() => {
27
+ UIManager.dispatchViewManagerCommand(
28
+ reactTag.current,
29
+ Platform.OS === 'ios'
30
+ ? UIManager.getViewManagerConfig('RNImageCrop').Commands.crop
31
+ : UIManager.getViewManagerConfig('RNImageCrop').Commands.crop.toString(),
32
+ Platform.OS === 'ios' ? [] : [reactTag.current],
33
+ )
34
+ }, [])
35
+
36
+ const onNativeCropped = useCallback(
37
+ ({ nativeEvent }: any) => {
38
+ const uri = nativeEvent.uri
39
+ if (onCropped) {
40
+ onCropped(uri)
41
+ }
42
+ },
43
+ [onCropped],
44
+ )
45
+
46
+ useImperativeHandle(
47
+ ref,
48
+ () => ({
49
+ crop,
50
+ }),
51
+ [crop],
52
+ )
53
+
54
+ return (
55
+ <CropViewNativeComponent
56
+ fileUri={fileUri}
57
+ cropStyle={cropStyle}
58
+ objectRect={objectRect}
59
+ onCropped={onNativeCropped}
60
+ style={style}
61
+ ref={mRef => {
62
+ reactTag.current = findNodeHandle(mRef)
63
+ }}
64
+ />
65
+ )
66
+ },
67
+ )
68
+
69
+ export default ImageCropView
@@ -0,0 +1,3 @@
1
+ export interface ImageCropViewRef {
2
+ crop: () => void
3
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ import ImageCropView from './ImageCropView'
2
+ import { ImageCropViewRef } from './ImageCropViewRef'
3
+ import { ObjectRect } from './typings'
4
+
5
+ export { ImageCropView }
6
+ export type { ImageCropViewRef, ObjectRect }
package/src/typings.ts ADDED
@@ -0,0 +1,6 @@
1
+ export interface ObjectRect {
2
+ top: number
3
+ left: number
4
+ width: number
5
+ height: number
6
+ }