@asaddevworld/image-crop 0.0.0-stage → 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.
@@ -0,0 +1,482 @@
1
+ import {
2
+ forwardRef,
3
+ useCallback,
4
+ useEffect,
5
+ useImperativeHandle,
6
+ useMemo,
7
+ useState,
8
+ } from 'react';
9
+ import { StyleSheet, View, type LayoutChangeEvent } from 'react-native';
10
+ import {
11
+ GestureDetector,
12
+ usePanGesture,
13
+ usePinchGesture,
14
+ useRotationGesture,
15
+ useSimultaneousGestures,
16
+ } from 'react-native-gesture-handler';
17
+ import {
18
+ Canvas,
19
+ Group,
20
+ Image,
21
+ Line,
22
+ Path,
23
+ Rect,
24
+ RoundedRect,
25
+ Skia,
26
+ vec,
27
+ } from '@shopify/react-native-skia';
28
+ import {
29
+ ReduceMotion,
30
+ runOnJS,
31
+ useAnimatedReaction,
32
+ useDerivedValue,
33
+ useSharedValue,
34
+ withSpring,
35
+ withTiming,
36
+ } from 'react-native-reanimated';
37
+ import type {
38
+ CropResult,
39
+ CropState,
40
+ ImageCropperHandle,
41
+ ImageCropperProps,
42
+ } from './types';
43
+ import {
44
+ clampTranslation,
45
+ coverScale,
46
+ frameFor,
47
+ frameInImage,
48
+ rubberBand,
49
+ snapRotation,
50
+ } from './utils/geometry';
51
+
52
+ const SPRING = {
53
+ damping: 28,
54
+ stiffness: 300,
55
+ mass: 1,
56
+ reduceMotion: ReduceMotion.System,
57
+ };
58
+
59
+ export const ImageCropper = forwardRef<ImageCropperHandle, ImageCropperProps>(
60
+ function ImageCropper(
61
+ {
62
+ image,
63
+ aspect,
64
+ frameInset = 24,
65
+ grid = 'gesture',
66
+ onChange,
67
+ minScaleFactor = 1,
68
+ maxScale = 8,
69
+ frameRadius = 0,
70
+ overlayColor = 'rgba(0,0,0,0.6)',
71
+ frameColor = '#FFFFFF',
72
+ style,
73
+ accessibilityLabel,
74
+ },
75
+ ref
76
+ ) {
77
+ const [view, setView] = useState({ width: 0, height: 0 });
78
+ const imageW = image.width();
79
+ const imageH = image.height();
80
+ const frame = useMemo(
81
+ () =>
82
+ frameFor(view.width, view.height, aspect, frameInset, imageW / imageH),
83
+ [view, aspect, frameInset, imageW, imageH]
84
+ );
85
+ const frameSv = useSharedValue(frame);
86
+ useEffect(() => {
87
+ frameSv.value = frame;
88
+ }, [frame, frameSv]);
89
+
90
+ const rotation = useSharedValue(0);
91
+ const scale = useSharedValue(1);
92
+ const x = useSharedValue(0);
93
+ const y = useSharedValue(0);
94
+ const gesturing = useSharedValue(0);
95
+ const startScale = useSharedValue(1);
96
+ const startX = useSharedValue(0);
97
+ const startY = useSharedValue(0);
98
+ const startRotation = useSharedValue(0);
99
+ const baseScale = useSharedValue(1);
100
+
101
+ const fit = useCallback(
102
+ (animated: boolean) => {
103
+ 'worklet';
104
+ const f = frameSv.value;
105
+ if (f.width === 0) {
106
+ return;
107
+ }
108
+ const s =
109
+ coverScale(imageW, imageH, f, rotation.value) * minScaleFactor;
110
+ baseScale.value = s;
111
+ if (animated) {
112
+ scale.value = withSpring(s, SPRING);
113
+ x.value = withSpring(0, SPRING);
114
+ y.value = withSpring(0, SPRING);
115
+ } else {
116
+ scale.value = s;
117
+ x.value = 0;
118
+ y.value = 0;
119
+ }
120
+ },
121
+ [
122
+ frameSv,
123
+ imageW,
124
+ imageH,
125
+ rotation,
126
+ minScaleFactor,
127
+ baseScale,
128
+ scale,
129
+ x,
130
+ y,
131
+ ]
132
+ );
133
+
134
+ useEffect(() => {
135
+ if (frame.width > 0) {
136
+ const s = coverScale(imageW, imageH, frame, 0) * minScaleFactor;
137
+ baseScale.value = s;
138
+ scale.value = s;
139
+ x.value = 0;
140
+ y.value = 0;
141
+ rotation.value = 0;
142
+ }
143
+ }, [
144
+ frame,
145
+ imageW,
146
+ imageH,
147
+ minScaleFactor,
148
+ baseScale,
149
+ scale,
150
+ x,
151
+ y,
152
+ rotation,
153
+ ]);
154
+
155
+ const settle = useCallback(() => {
156
+ 'worklet';
157
+ const f = frameSv.value;
158
+ const snapped = snapRotation(rotation.value);
159
+ rotation.value = withSpring(snapped, SPRING);
160
+ const minS = coverScale(imageW, imageH, f, snapped) * minScaleFactor;
161
+ baseScale.value = minS;
162
+ const s = Math.min(maxScale, Math.max(minS, scale.value));
163
+ const clamped = clampTranslation(
164
+ x.value,
165
+ y.value,
166
+ imageW,
167
+ imageH,
168
+ s,
169
+ f,
170
+ snapped
171
+ );
172
+ scale.value = withSpring(s, SPRING);
173
+ x.value = withSpring(clamped.x, SPRING);
174
+ y.value = withSpring(clamped.y, SPRING);
175
+ }, [
176
+ frameSv,
177
+ rotation,
178
+ imageW,
179
+ imageH,
180
+ minScaleFactor,
181
+ maxScale,
182
+ baseScale,
183
+ scale,
184
+ x,
185
+ y,
186
+ ]);
187
+
188
+ const pan = usePanGesture({
189
+ minPointers: 1,
190
+ maxPointers: 2,
191
+ onBegin: () => {
192
+ 'worklet';
193
+ startX.value = x.value;
194
+ startY.value = y.value;
195
+ gesturing.value = withTiming(1, { duration: 120 });
196
+ },
197
+ onUpdate: (e) => {
198
+ 'worklet';
199
+ const f = frameSv.value;
200
+ const nx = startX.value + e.translationX;
201
+ const ny = startY.value + e.translationY;
202
+ const c = clampTranslation(
203
+ nx,
204
+ ny,
205
+ imageW,
206
+ imageH,
207
+ scale.value,
208
+ f,
209
+ rotation.value
210
+ );
211
+ x.value =
212
+ c.x + Math.sign(nx - c.x) * rubberBand(Math.abs(nx - c.x), f.width);
213
+ y.value =
214
+ c.y + Math.sign(ny - c.y) * rubberBand(Math.abs(ny - c.y), f.height);
215
+ },
216
+ onFinalize: () => {
217
+ 'worklet';
218
+ gesturing.value = withTiming(0, { duration: 250 });
219
+ settle();
220
+ },
221
+ });
222
+
223
+ const pinch = usePinchGesture({
224
+ onBegin: () => {
225
+ 'worklet';
226
+ startScale.value = scale.value;
227
+ startX.value = x.value;
228
+ startY.value = y.value;
229
+ },
230
+ onUpdate: (e) => {
231
+ 'worklet';
232
+ const f = frameSv.value;
233
+ let s = startScale.value * e.scale;
234
+ const minS = baseScale.value;
235
+ if (s < minS) {
236
+ s = minS - rubberBand(minS - s, minS);
237
+ } else if (s > maxScale) {
238
+ s = maxScale + rubberBand(s - maxScale, maxScale);
239
+ }
240
+ // Zoom around the focal point: keep the point under the fingers fixed.
241
+ const fx = e.focalX - (f.x + f.width / 2);
242
+ const fy = e.focalY - (f.y + f.height / 2);
243
+ const k = s / startScale.value;
244
+ x.value = fx - (fx - startX.value) * k;
245
+ y.value = fy - (fy - startY.value) * k;
246
+ scale.value = s;
247
+ },
248
+ onFinalize: () => {
249
+ 'worklet';
250
+ settle();
251
+ },
252
+ });
253
+
254
+ const rotate = useRotationGesture({
255
+ onBegin: () => {
256
+ 'worklet';
257
+ startRotation.value = rotation.value;
258
+ },
259
+ onUpdate: (e) => {
260
+ 'worklet';
261
+ rotation.value = startRotation.value + (e.rotation * 180) / Math.PI;
262
+ },
263
+ onFinalize: () => {
264
+ 'worklet';
265
+ settle();
266
+ },
267
+ });
268
+
269
+ const gesture = useSimultaneousGestures(pan, pinch, rotate);
270
+
271
+ const notify = useCallback(
272
+ (state: CropState) => {
273
+ onChange?.(state);
274
+ },
275
+ [onChange]
276
+ );
277
+ useAnimatedReaction(
278
+ () => ({
279
+ scale: scale.value,
280
+ x: x.value,
281
+ y: y.value,
282
+ rotation: rotation.value,
283
+ }),
284
+ (current, previous) => {
285
+ if (
286
+ previous &&
287
+ (current.scale !== previous.scale ||
288
+ current.x !== previous.x ||
289
+ current.y !== previous.y ||
290
+ current.rotation !== previous.rotation)
291
+ ) {
292
+ runOnJS(notify)(current);
293
+ }
294
+ }
295
+ );
296
+
297
+ const imageTransform = useDerivedValue(() => {
298
+ const f = frameSv.value;
299
+ return [
300
+ { translateX: f.x + f.width / 2 + x.value },
301
+ { translateY: f.y + f.height / 2 + y.value },
302
+ { rotate: (rotation.value * Math.PI) / 180 },
303
+ { scale: scale.value },
304
+ { translateX: -imageW / 2 },
305
+ { translateY: -imageH / 2 },
306
+ ];
307
+ });
308
+
309
+ const overlayPath = useMemo(() => {
310
+ const b = Skia.PathBuilder.Make();
311
+ b.addRect({ x: 0, y: 0, width: view.width, height: view.height });
312
+ b.addRRect(Skia.RRectXY(frame, frameRadius, frameRadius));
313
+ return b.build();
314
+ }, [view, frame, frameRadius]);
315
+
316
+ const gridOpacity = useDerivedValue(() =>
317
+ grid === 'always' ? 1 : grid === 'never' ? 0 : gesturing.value * 0.9
318
+ );
319
+
320
+ useImperativeHandle(
321
+ ref,
322
+ () => ({
323
+ getState: () => ({
324
+ scale: scale.value,
325
+ x: x.value,
326
+ y: y.value,
327
+ rotation: rotation.value,
328
+ }),
329
+ rotate: (degrees) => {
330
+ const target = Math.round(rotation.value / 90) * 90 + degrees;
331
+ rotation.value = withSpring(target, SPRING, (finished) => {
332
+ if (finished) {
333
+ fit(true);
334
+ }
335
+ });
336
+ },
337
+ reset: () => {
338
+ rotation.value = withSpring(0, SPRING);
339
+ fit(true);
340
+ },
341
+ crop: async (options) => {
342
+ const region = frameInImage(
343
+ imageW,
344
+ imageH,
345
+ scale.value,
346
+ x.value,
347
+ y.value,
348
+ frame,
349
+ rotation.value
350
+ );
351
+ const ratio = frame.width / frame.height;
352
+ const outW = Math.round(
353
+ options?.width ??
354
+ (options?.height ? options.height * ratio : region.width)
355
+ );
356
+ const outH = Math.round(options?.height ?? outW / ratio);
357
+ const surface = Skia.Surface.MakeOffscreen(outW, outH);
358
+ if (!surface) {
359
+ throw new Error('Could not create an offscreen surface.');
360
+ }
361
+ const canvas = surface.getCanvas();
362
+ const r =
363
+ (((Math.round(rotation.value / 90) * 90) % 360) + 360) % 360;
364
+ canvas.save();
365
+ // Rotate the output around its centre, then draw the source region to fill it.
366
+ canvas.translate(outW / 2, outH / 2);
367
+ canvas.rotate(r, 0, 0);
368
+ const drawW = r === 90 || r === 270 ? outH : outW;
369
+ const drawH = r === 90 || r === 270 ? outW : outH;
370
+ canvas.drawImageRect(
371
+ image,
372
+ {
373
+ x: region.x,
374
+ y: region.y,
375
+ width: region.width,
376
+ height: region.height,
377
+ },
378
+ { x: -drawW / 2, y: -drawH / 2, width: drawW, height: drawH },
379
+ Skia.Paint()
380
+ );
381
+ canvas.restore();
382
+ surface.flush();
383
+ const out = surface.makeImageSnapshot();
384
+ const result: CropResult = {
385
+ image: out,
386
+ base64: out.encodeToBase64(),
387
+ width: outW,
388
+ height: outH,
389
+ };
390
+ return result;
391
+ },
392
+ }),
393
+ [scale, x, y, rotation, fit, imageW, imageH, frame, image]
394
+ );
395
+
396
+ const onLayout = useCallback((e: LayoutChangeEvent) => {
397
+ setView({
398
+ width: Math.round(e.nativeEvent.layout.width),
399
+ height: Math.round(e.nativeEvent.layout.height),
400
+ });
401
+ }, []);
402
+
403
+ const thirds = useMemo(() => {
404
+ const lines: {
405
+ p1: { x: number; y: number };
406
+ p2: { x: number; y: number };
407
+ }[] = [];
408
+ for (let i = 1; i < 3; i++) {
409
+ lines.push({
410
+ p1: { x: frame.x + (frame.width * i) / 3, y: frame.y },
411
+ p2: { x: frame.x + (frame.width * i) / 3, y: frame.y + frame.height },
412
+ });
413
+ lines.push({
414
+ p1: { x: frame.x, y: frame.y + (frame.height * i) / 3 },
415
+ p2: { x: frame.x + frame.width, y: frame.y + (frame.height * i) / 3 },
416
+ });
417
+ }
418
+ return lines;
419
+ }, [frame]);
420
+
421
+ return (
422
+ <GestureDetector gesture={gesture}>
423
+ <View
424
+ style={[styles.root, style]}
425
+ onLayout={onLayout}
426
+ accessible
427
+ accessibilityLabel={
428
+ accessibilityLabel ??
429
+ 'Image cropper. Pinch to zoom, drag to move, rotate with two fingers.'
430
+ }
431
+ >
432
+ {view.width > 0 ? (
433
+ <Canvas style={{ width: view.width, height: view.height }}>
434
+ <Group transform={imageTransform}>
435
+ <Image
436
+ image={image}
437
+ x={0}
438
+ y={0}
439
+ width={imageW}
440
+ height={imageH}
441
+ fit="fill"
442
+ />
443
+ </Group>
444
+ <Path
445
+ path={overlayPath}
446
+ color={overlayColor}
447
+ fillType="evenOdd"
448
+ />
449
+ <RoundedRect
450
+ x={frame.x}
451
+ y={frame.y}
452
+ width={frame.width}
453
+ height={frame.height}
454
+ r={frameRadius}
455
+ color={frameColor}
456
+ style="stroke"
457
+ strokeWidth={1.5}
458
+ />
459
+ <Group opacity={gridOpacity}>
460
+ {thirds.map((l, i) => (
461
+ <Line
462
+ key={i}
463
+ p1={vec(l.p1.x, l.p1.y)}
464
+ p2={vec(l.p2.x, l.p2.y)}
465
+ color={frameColor}
466
+ strokeWidth={0.75}
467
+ opacity={0.8}
468
+ />
469
+ ))}
470
+ </Group>
471
+ <Rect x={0} y={0} width={0} height={0} />
472
+ </Canvas>
473
+ ) : null}
474
+ </View>
475
+ </GestureDetector>
476
+ );
477
+ }
478
+ );
479
+
480
+ const styles = StyleSheet.create({
481
+ root: { flex: 1, overflow: 'hidden', backgroundColor: '#000' },
482
+ });
package/src/index.tsx ADDED
@@ -0,0 +1,14 @@
1
+ export { ImageCropper } from './ImageCropper';
2
+ export {
3
+ frameFor,
4
+ coverScale,
5
+ clampTranslation,
6
+ frameInImage,
7
+ snapRotation,
8
+ } from './utils/geometry';
9
+ export type {
10
+ CropResult,
11
+ CropState,
12
+ ImageCropperHandle,
13
+ ImageCropperProps,
14
+ } from './types';
package/src/types.ts ADDED
@@ -0,0 +1,40 @@
1
+ import type { SkImage } from '@shopify/react-native-skia';
2
+
3
+ export interface CropState {
4
+ scale: number;
5
+ x: number;
6
+ y: number;
7
+ /** Degrees. */
8
+ rotation: number;
9
+ }
10
+
11
+ export interface CropResult {
12
+ image: SkImage;
13
+ base64: string;
14
+ width: number;
15
+ height: number;
16
+ }
17
+
18
+ export interface ImageCropperProps {
19
+ image: SkImage;
20
+ /** Width / height. Undefined keeps the image ratio. */
21
+ aspect?: number;
22
+ /** Space around the frame, px. Default 24. */
23
+ frameInset?: number;
24
+ grid?: 'always' | 'gesture' | 'never';
25
+ onChange?: (state: CropState) => void;
26
+ minScaleFactor?: number;
27
+ maxScale?: number;
28
+ frameRadius?: number;
29
+ overlayColor?: string;
30
+ frameColor?: string;
31
+ style?: object;
32
+ accessibilityLabel?: string;
33
+ }
34
+
35
+ export interface ImageCropperHandle {
36
+ crop: (options?: { width?: number; height?: number }) => Promise<CropResult>;
37
+ rotate: (degrees: 90 | -90) => void;
38
+ reset: () => void;
39
+ getState: () => CropState;
40
+ }
@@ -0,0 +1,129 @@
1
+ export interface Rect {
2
+ x: number;
3
+ y: number;
4
+ width: number;
5
+ height: number;
6
+ }
7
+
8
+ /** Frame rectangle centred in the viewport, sized by the aspect ratio. */
9
+ export function frameFor(
10
+ viewW: number,
11
+ viewH: number,
12
+ aspect: number | undefined,
13
+ inset: number,
14
+ imageAspect: number
15
+ ): Rect {
16
+ const ratio = aspect ?? imageAspect;
17
+ const maxW = Math.max(0, viewW - inset * 2);
18
+ const maxH = Math.max(0, viewH - inset * 2);
19
+ let width = maxW;
20
+ let height = width / ratio;
21
+ if (height > maxH) {
22
+ height = maxH;
23
+ width = height * ratio;
24
+ }
25
+ return { x: (viewW - width) / 2, y: (viewH - height) / 2, width, height };
26
+ }
27
+
28
+ /** Scale at which the (rotated) image fully covers the frame. */
29
+ export function coverScale(
30
+ imageW: number,
31
+ imageH: number,
32
+ frame: Rect,
33
+ rotation: number
34
+ ): number {
35
+ 'worklet';
36
+ const quarter = Math.round(rotation / 90) % 2 !== 0;
37
+ const w = quarter ? imageH : imageW;
38
+ const h = quarter ? imageW : imageH;
39
+ return Math.max(frame.width / w, frame.height / h);
40
+ }
41
+
42
+ /**
43
+ * Clamp a translation so the scaled, 90-degree-rotated image still covers the frame.
44
+ * Translation is the offset of the image centre from the frame centre.
45
+ */
46
+ export function clampTranslation(
47
+ x: number,
48
+ y: number,
49
+ imageW: number,
50
+ imageH: number,
51
+ scale: number,
52
+ frame: Rect,
53
+ rotation: number
54
+ ): { x: number; y: number } {
55
+ 'worklet';
56
+ const quarter = Math.round(rotation / 90) % 2 !== 0;
57
+ const w = (quarter ? imageH : imageW) * scale;
58
+ const h = (quarter ? imageW : imageH) * scale;
59
+ const maxX = Math.max(0, (w - frame.width) / 2);
60
+ const maxY = Math.max(0, (h - frame.height) / 2);
61
+ return {
62
+ x: Math.min(maxX, Math.max(-maxX, x)),
63
+ y: Math.min(maxY, Math.max(-maxY, y)),
64
+ };
65
+ }
66
+
67
+ export function rubberBand(
68
+ distance: number,
69
+ dimension: number,
70
+ coefficient = 0.55
71
+ ): number {
72
+ 'worklet';
73
+ if (distance <= 0 || dimension <= 0) {
74
+ return 0;
75
+ }
76
+ return (1 - 1 / ((distance * coefficient) / dimension + 1)) * dimension;
77
+ }
78
+
79
+ /** Snap to the nearest multiple of 90 when within `tolerance` degrees. */
80
+ export function snapRotation(degrees: number, tolerance = 10): number {
81
+ 'worklet';
82
+ const nearest = Math.round(degrees / 90) * 90 + 0;
83
+ return Math.abs(degrees - nearest) <= tolerance ? nearest || 0 : degrees;
84
+ }
85
+
86
+ /**
87
+ * The frame rectangle in image pixel coordinates for a transform.
88
+ * Only 90-degree rotations map to an axis-aligned rectangle; free angles are rounded.
89
+ */
90
+ export function frameInImage(
91
+ imageW: number,
92
+ imageH: number,
93
+ scale: number,
94
+ x: number,
95
+ y: number,
96
+ frame: Rect,
97
+ rotation: number
98
+ ): Rect {
99
+ const r = (((Math.round(rotation / 90) * 90) % 360) + 360) % 360;
100
+ const quarter = r === 90 || r === 270;
101
+ const w = (quarter ? imageH : imageW) * scale;
102
+ const h = (quarter ? imageW : imageH) * scale;
103
+ // Top-left of the drawn (rotated) image in view space, relative to the frame.
104
+ const left = frame.width / 2 + x - w / 2;
105
+ const top = frame.height / 2 + y - h / 2;
106
+ // Frame in rotated-image space (0..w, 0..h).
107
+ const fx = -left;
108
+ const fy = -top;
109
+ const fw = frame.width;
110
+ const fh = frame.height;
111
+ // Undo rotation to get coordinates in the original image.
112
+ let ox = fx / scale;
113
+ let oy = fy / scale;
114
+ let ow = fw / scale;
115
+ let oh = fh / scale;
116
+ if (r === 90) {
117
+ [ox, oy, ow, oh] = [oy, imageH - ox - ow, oh, ow];
118
+ } else if (r === 180) {
119
+ [ox, oy] = [imageW - ox - ow, imageH - oy - oh];
120
+ } else if (r === 270) {
121
+ [ox, oy, ow, oh] = [imageW - oy - oh, ox, oh, ow];
122
+ }
123
+ return {
124
+ x: Math.max(0, Math.min(imageW, ox)),
125
+ y: Math.max(0, Math.min(imageH, oy)),
126
+ width: Math.max(1, Math.min(imageW - Math.max(0, ox), ow)),
127
+ height: Math.max(1, Math.min(imageH - Math.max(0, oy), oh)),
128
+ };
129
+ }