### Start Example App Packager
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Starts the Metro server for the example application. This is necessary to run and test changes made to the library in the example app. Native code changes may require a rebuild of the example app.
```shell
yarn example start
```
--------------------------------
### Start Documentation Website Development Server
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Starts a local development server for the VitePress documentation website. This allows developers to preview documentation changes in real-time.
```shell
yarn docs docs:dev
```
--------------------------------
### Run Example App on Web
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Builds and runs the example application on a web browser. This command allows testing library functionality in a web environment.
```shell
yarn example web
```
--------------------------------
### Run Example App on iOS
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Builds and runs the example application on an iOS simulator or device. This command is used to test library changes in a real iOS environment.
```shell
yarn example ios
```
--------------------------------
### Run Example App on Android
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Builds and runs the example application on an Android device or emulator. This command is used to test library changes in a real Android environment.
```shell
yarn example android
```
--------------------------------
### Install Project Dependencies with Yarn
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Installs all necessary project dependencies for the monorepo using Yarn workspaces. This command should be run in the root directory of the project to set up the development environment.
```shell
yarn
```
--------------------------------
### Preview Documentation Website Production Build
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Runs a local server to preview the production build of the documentation website. This is useful for testing the final output before deployment.
```shell
yarn docs docs:preview
```
--------------------------------
### Build Documentation Website
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Builds a static production version of the documentation website using VitePress. This command generates the files needed for deployment.
```shell
yarn docs docs:build
```
--------------------------------
### Basic Skia Image Setup with fitContainer
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/guides/skia.md
Demonstrates the initial setup for displaying an image using React Native Skia. It utilizes the `useImage` hook to load an image from a URI and `fitContainer` to calculate the appropriate dimensions for displaying the image within the available screen space. The `origin` property is set to center the transformation of the image.
```tsx
import React from 'react';
import { View, useWindowDimensions } from 'react-native';
import { Canvas, Image, useImage } from '@shopify/react-native-skia';
import { fitContainer } from 'react-native-zoom-toolkit';
const uri =
'https://assets-global.website-files.com/63634f4a7b868a399577cf37/64665685a870fadf4bb171c2_labrador%20americano.jpg';
const App = () => {
const image = useImage(uri);
const { width, height } = useWindowDimensions();
if (image === null) {
return null;
}
const aspectRatio = image.width() / image.height();
const imageSize = fitContainer(aspectRatio, { width, height });
const x = 0;
const y = (height - imageSize.height) / 2;
const centerX = x + imageSize.width / 2;
const centerY = y + imageSize.height / 2;
return (
);
};
export default App;
```
--------------------------------
### Install Dependencies for React Native Zoom Toolkit
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/guides/cropzoomexpo.md
Installs the react-native-zoom-toolkit and its peer dependencies in an Expo managed project. Requires Node.js and npm/yarn. This command installs packages needed for image cropping and manipulation.
```sh
npx create-expo-app "crop-example" --template "blank-typescript"
cd crop-example
npx expo install react-native-reanimated react-native-gesture-handler @shopify/react-native-skia react-native-zoom-toolkit
```
--------------------------------
### Publish New Versions with Release-it
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Publishes a new version of the library to npm using the release-it tool. This script automates version bumping, tagging, and release creation.
```shell
yarn release
```
--------------------------------
### Run Unit Tests with Jest
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Executes all unit tests defined in the project using Jest. This command is crucial for verifying the correctness of new features and bug fixes.
```shell
yarn test
```
--------------------------------
### React Native CropZoom Image Cropping Example
Source: https://context7.com/glazzes/react-native-zoom-toolkit/llms.txt
Demonstrates how to use the CropZoom component to crop an image in React Native. It includes functionality for cropping, rotating, and flipping the image, along with handling component references and state updates. This example requires the 'react-native-zoom-toolkit' library.
```tsx
import React, { useRef, useState } from 'react';
import { Image, View, Button, Alert } from 'react-native';
import { CropZoom } from 'react-native-zoom-toolkit';
import type { CropZoomRefType } from 'react-native-zoom-toolkit';
const ImageCropper = () => {
const cropRef = useRef(null);
const [imageResolution] = useState({ width: 1920, height: 1080 });
const handleCrop = () => {
if (!cropRef.current) return;
const result = cropRef.current.crop();
console.log('Crop coordinates:', {
x: result.crop.originX,
y: result.crop.originY,
width: result.crop.width,
height: result.crop.height,
});
console.log('Transformations:', {
rotation: result.context.rotationAngle,
flipHorizontal: result.context.flipHorizontal,
flipVertical: result.context.flipVertical,
});
if (result.resize) {
console.log('Resized dimensions:', result.resize);
}
};
const handleRotate = () => {
cropRef.current?.rotate(true, true, (angle) => {
console.log('Rotated to angle:', angle);
});
};
const handleFlipHorizontal = () => {
cropRef.current?.flipHorizontal(true, (angle) => {
console.log('Flipped horizontal:', angle);
});
};
const CropOverlay = () => (
);
return (
{
console.log('Crop state:', state.scale, state.rotate);
}}
>
);
};
export default ImageCropper;
```
--------------------------------
### Initialize and Use CropZoom Component
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/cropzoom.md
Demonstrates how to initialize the CropZoom component, obtain a reference to its methods using useRef, and call the 'crop' method. It also shows the basic setup of the CropZoom component in a React Native application.
```tsx
import { useRef } from 'react';
import { CropZoom, type CropZoomRefType } from 'react-native-zoom-toolkit';
const ref = useRef(null);
ref.current?.crop(200);
;
```
--------------------------------
### Fix Linting Errors with ESLint
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Automatically fixes code formatting and style issues detected by ESLint. This command should be run to ensure the code adheres to the project's linting standards.
```shell
yarn lint --fix
```
--------------------------------
### onZoomBegin Callback for Zoom Initiation
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/gallery.md
The onZoomBegin callback is triggered when a component starts zooming from its base scale (scale value of 1). It receives the index of the component being zoomed.
```typescript
// Example usage within a React component
const handleZoomBegin = (index: number) => {
console.log(`Zoom started for item at index: ${index}`);
};
;
// Type for the callback function
type OnZoomBeginCallback = (index: number) => void;
```
--------------------------------
### Lint Project Files with ESLint
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Lints all project files using ESLint to enforce code style and identify potential code quality issues. This command helps maintain code consistency across the project.
```shell
yarn lint
```
--------------------------------
### Handle Pinch Gesture Start in React Native
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/snapbackzoom.md
The `onPinchStart` callback is invoked when a pinch gesture begins. It provides a `PinchGestureEvent` object with relevant gesture data. This functionality relies on React Native Gesture Handler.
```typescript
function onPinchStart(e: PinchGestureEvent): void;
```
--------------------------------
### Basic and Complex SnapbackZoom Usage in React Native
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/snapbackzoom.md
Demonstrates how to use the SnapbackZoom component in React Native for both simple and complex scenarios. The complex example includes optional gesture event handlers and timing configurations. Ensure child components are measurable and avoid relative units or absolute positioning within the child.
```jsx
import { SnapbackZoom } from "react-native-zoom-toolkit"
// Simple use case
// Complex use case
console.log(e)}
onDoubleTap={(e) => console.log(e)}
onPinchStart={(e) => console.log(e)}
onPinchEnd={(e) => console.log(e)}
onUpdate={(e) => {
'worklet';
console.log(e);
}}
onGestureEnd={() => console.log('animation finished!')}
>
```
--------------------------------
### Using ResumableZoom for Image Detail View in React Native
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/resumablezoom.md
Demonstrates how to integrate the ResumableZoom component to display a full-screen image with zoom and pan capabilities. It utilizes hooks for window dimensions and image resolution, applying a 'fitContainer' utility to size the image appropriately. The example requires 'react-native-zoom-toolkit' for ResumableZoom, fitContainer, and useImageResolution.
```jsx
import React from 'react';
import { Image, useWindowDimensions } from 'react-native';
import {
fitContainer,
ResumableZoom,
useImageResolution,
} from 'react-native-zoom-toolkit';
const uri =
'https://assets-global.website-files.com/63634f4a7b868a399577cf37/64665685a870fadf4bb171c2_labrador%20americano.jpg';
const App = () => {
const { width, height } = useWindowDimensions();
const { isFetching, resolution } = useImageResolution({ uri });
if (isFetching || resolution === undefined) {
return null;
}
const size = fitContainer(resolution.width / resolution.height, {
width,
height,
});
return (
);
};
export default App;
```
--------------------------------
### Typecheck Project with TypeScript
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/CONTRIBUTING.md
Performs type checking on the entire project using TypeScript. This command ensures code adheres to defined types and helps catch potential errors before committing.
```shell
yarn typecheck
```
--------------------------------
### React Native Zoom Toolkit: Reset Method Example
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/resumablezoom.md
Demonstrates how to use the reset method of the ResumableZoom component via a ref. This is useful for programmatically resetting the zoom state. It requires importing useRef and specific types from the library.
```tsx
import { useRef } from 'react';
import {
ResumableZoom,
type ResumableZoomRefType,
} from 'react-native-zoom-toolkit';
const ref = useRef(null);
ref.current?.reset(false);
;
```
--------------------------------
### Get Image Resolution with useImageResolution Hook (React Native)
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/utilities/useimageresolution.md
Demonstrates how to use the `useImageResolution` hook to fetch the width and height of network, bundle, or base64 encoded images. It shows the import statement and different ways to invoke the hook based on the image source. The hook returns fetching status, resolution dimensions, and potential errors.
```jsx
import { useImageResolution } from 'react-native-zoom-toolkit';
// Network image
const { isFetching, resolution, error } = useImageResolution({
uri: 'url to some network image',
headers: {
Authorization: 'some bearer token',
},
});
// Bundle image
const { isFetching, resolution, error } = useImageResolution(
require('path to your bundle image asset')
);
// Base64 image
const { isFetching, resolution, error } = useImageResolution({
uri: 'your base64 string',
});
```
--------------------------------
### Handle Gesture Updates with Worklets in React Native
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/snapbackzoom.md
The `onUpdate` callback is a worklet function that triggers from the start of a pinch gesture until the snap back animation completes. It's useful for synchronizing gesture state with other components, receiving a `SnapbackZoomState` object.
```typescript
function onUpdate(state: SnapbackZoomState): void;
```
--------------------------------
### Configure Image Resizing with resizeConfig
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/snapbackzoom.md
This example demonstrates how to use the `resizeConfig` object to manage the aspect ratio of an image within a `SnapbackZoom` component. The `size` property defines the base dimensions, `aspectRatio` is derived from the original image, and `scale` indicates at which zoom level the aspect ratio should be enforced. The child image component requires `{width: '100%', height: '100%'}` styles.
```tsx
const resizeConfig = {
size: { width: 200, height: 200 }, // size of your tile
aspectRatio: 1920 / 1080, // aspect ratio based on the size of your image/video
scale: 2 // at which scale the aspect ratio is no longer compromised
}
{/* Use width and height properties not flex: 1 */ }
```
--------------------------------
### Integrating ResumableZoom with Skia for Interactive Images
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/guides/skia.md
This example shows how to overlay `ResumableZoom` on a Skia `Canvas` to enable interactive zoom and pan gestures on an image. It uses the `useTransformationState` hook from `react-native-zoom-toolkit` to manage the transformation state and applies it to both the `Skia` `Image` and the `ResumableZoom` component. The nested `View` inside `ResumableZoom` must match the size of the Skia image for proper alignment.
```tsx
import React from 'react';
import { View, useWindowDimensions } from 'react-native';
import { Canvas, Image, useImage } from '@shopify/react-native-skia';
import { fitContainer, ResumableZoom, useTransformationState } from 'react-native-zoom-toolkit';
const uri =
'https://assets-global.website-files.com/63634f4a7b868a399577cf37/64665685a870fadf4bb171c2_labrador%20americano.jpg';
const App = () => {
const image = useImage(uri);
const { width, height } = useWindowDimensions();
const { onUpdate, transform } = useTransformationState('resumable');
if (image === null) {
return null;
}
const aspectRatio = image.width() / image.height();
const imageSize = fitContainer(aspectRatio, { width, height });
const x = 0;
const y = (height - imageSize.height) / 2;
const centerX = x + imageSize.width / 2;
const centerY = y + imageSize.height / 2;
return (
);
};
export default App;
```
--------------------------------
### Get CropZoom Component State
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/cropzoom.md
The 'getState' method is used to retrieve the current internal transformation values of the CropZoom component. This method takes no arguments and returns an object conforming to the CropZoomState type.
```typescript
const currentState = ref.current?.getState();
```
--------------------------------
### Implement SnapbackZoom for Image Previews (React Native)
Source: https://context7.com/glazzes/react-native-zoom-toolkit/llms.txt
Demonstrates the usage of SnapbackZoom component for creating temporary zoomable image previews. It requires React Native, 'react-native-zoom-toolkit', 'react-native-reanimated', and 'react-native-gesture-handler'. The component takes configuration for resizing, timing, and event handlers for pinch gestures.
```tsx
import React from 'react';
import { Image, View } from 'react-native';
import { SnapbackZoom } from 'react-native-zoom-toolkit';
const ImagePreview = () => {
const handlePinchStart = (event) => {
console.log('Pinch started:', event);
};
const handlePinchEnd = (event) => {
console.log('Pinch ended:', event);
};
const handleUpdate = (state) => {
console.log('Current state:', {
scale: state.scale,
translateX: state.translateX,
translateY: state.translateY,
});
};
return (
console.log('Gesture ended')}
>
);
};
export default ImagePreview;
```
--------------------------------
### Configuration and Animation Callbacks
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/snapbackzoom.md
This section covers configuration options like long press duration and callbacks related to the zoom animation's update and completion.
```APIDOC
## Configuration and Animation Callbacks
### longPressDuration
Minimum time expressed in milliseconds required to trigger the long press gesture event. Expect values greater than 250 to avoid collisions with tap and double tap gestures.
- **Type**: `number`
- **Default**: `500`
### onUpdate
Worklet callback triggered from the moment the pinch gesture starts until the snap back animation finishes. Ideal if you need to mirror the current state of the gesture to some other component. See [SnapbackZoomState](#snapbackzoomstate).
- **Type**: `(state: SnapbackZoomState) => void`
- **Default**: `undefined`
- **Additional Info**: See [worklets](https://docs.swmansion.com/react-native-reanimated/docs/2.x/fundamentals/worklets/)
### onGestureEnd
Callback triggered once the snap back animation has finished.
- **Type**: `() => void`
- **Default**: `undefined`
```
--------------------------------
### Handle Long Press Gesture Start in React Native
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/snapbackzoom.md
The `onLongPress` callback is triggered at the beginning of a long press gesture, providing a `LongPressEvent` object. This functionality is dependent on React Native Gesture Handler.
```typescript
function onLongPress(e: LongPressEvent): void;
```
--------------------------------
### React Native Zoom Toolkit: Long Press Configuration and Callback
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/resumablezoom.md
Details the `longPressDuration` property and the `onLongPress` callback for the zoom component. `longPressDuration` sets the minimum time in milliseconds for a long press, and `onLongPress` is triggered when the gesture starts.
```typescript
// Example usage structure (actual implementation depends on event data usage)
const handleLongPress = (e: LongPressEvent) => {
console.log('Long press detected:', e);
};
// In your component:
//
```
--------------------------------
### Implement React Native Zoomable Gallery Component
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/gallery.md
This snippet demonstrates how to implement a full-screen image gallery using the Gallery component from 'react-native-zoom-toolkit'. It showcases data binding, item rendering, key extraction, and tap handling, along with custom transition configuration. Ensure React Native performance recommendations for list components are followed.
```tsx
import React, { useCallback, useRef } from 'react';
import {
stackTransition,
Gallery,
type GalleryType,
} from 'react-native-zoom-toolkit';
import GalleryImage from './GalleryImage';
const images = [
'https://kutyaknak.hu/shop_ordered/73803/pic/gsp.jpg',
'https://cdn.britannica.com/02/132502-050-F4667944/macaw.jpg',
'https://assets-global.website-files.com/63634f4a7b868a399577cf37/64665685a870fadf4bb171c2_labrador%20americano.jpg',
'https://i0.wp.com/bcc-newspack.s3.amazonaws.com/uploads/2023/05/052323-Foxes-in-Millennium-Park-Colin-Boyle-9124.jpg?fit=1650%2C1099&ssl=1',
];
const GalleryExample = () => {
const ref = useRef(null);
// Remember to memoize your callbacks properly to keep a decent performance
const renderItem = useCallback((item: string, index: number) => {
return ;
}, []);
const keyExtractor = useCallback((item: string, index: number) => {
return `${item}-${index}`;
}, []);
const onTap = useCallback((_, index: number) => {
console.log(`Tapped on index ${index}`);
}, []);
const transition = useCallback(stackTransition, []);
return (
);
};
export default GalleryExample;
```
--------------------------------
### React Native Image Cropper Component (App.tsx)
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/guides/cropzoomexpo.md
The main application file demonstrating the use of CropZoom from react-native-zoom-toolkit. It sets up the image source, defines the crop area, renders an SVG overlay, and includes controls for manipulation. Requires Expo, react-native-reanimated, react-native-gesture-handler, and @shopify/react-native-skia.
```tsx
import React, { useRef, useState } from 'react';
import {
Image,
Pressable,
View,
StyleSheet,
useWindowDimensions,
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import {
CropZoom,
useImageResolution,
type CropZoomType,
type SizeVector,
} from 'react-native-zoom-toolkit';
import Controls from './Controls';
import SVGOverlay from './SVGOverlay';
const IMAGE =
'https://assets-global.website-files.com/63634f4a7b868a399577cf37/64665685a870fadf4bb171c2_labrador%20americano.jpg';
const App = ({}) => {
const cropRef = useRef(null);
const { width } = useWindowDimensions();
const { isFetching, resolution } = useImageResolution({ uri: IMAGE });
const [result, setResult] = useState(undefined);
const cropSize: SizeVector = {
width: width * 0.8,
height: width * 0.8,
};
const renderOverlay = () => {
return ;
};
if (isFetching || resolution === undefined) {
return null;
}
return (
{
*
* Display the resulting image on top of the crop screen
*/}
{result !== undefined ? (
setResult(undefined)}
style={{ position: 'absolute' }}
>
) : null}
);
};
const styles = StyleSheet.create({
root: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#121212',
},
image: {
width: '100%',
height: '100%',
},
});
export default App;
```
--------------------------------
### CropContextResult Object Structure
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/cropzoom.md
Defines the structure for specifying crop, context, and resize parameters for image and video manipulation.
```APIDOC
## CropContextResult Object
### Description
This object encapsulates parameters for cropping, context (rotation and flipping), and resizing an image or video.
### Parameters
#### crop
- **originX** (number) - The x-coordinate of the top-left corner of the crop area.
- **originY** (number) - The y-coordinate of the top-left corner of the crop area.
- **width** (number) - The width of the crop area.
- **height** (number) - The height of the crop area.
#### context
- **rotationAngle** (number) - The angle in degrees to rotate the image/video.
- **flipHorizontal** (boolean) - Whether to flip the image/video horizontally.
- **flipVertical** (boolean) - Whether to flip the image/video vertically.
#### resize
- **width** (number) - The target width after resizing.
- **height** (number) - The target height after resizing.
*Note: The `resize` property is optional and will be `undefined` if the `crop` method is called without a `fixedWidth` argument.*
```
--------------------------------
### Managing Zoom Scale with useTransformationState Hook in TypeScript
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/guides/downscale.md
This example shows how to use the `useTransformationState` hook to manage zoom state. It provides an `onUpdate` function and a `state` object containing the current scale shared value.
```ts
const { onUpdate, state } = useTransformationState('resumable');
state.scale; // Holds the shared value describing the current scale
onUpdate; // Update worklet function
```
--------------------------------
### React Native Zoom Toolkit - Methods
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/cropzoom.md
All methods are accessible through a ref object. This section details the available methods for manipulating the zoom and transformation state of the component.
```APIDOC
## Methods (via ref)
### getState
**Description**: Request internal transformation values of this component at the moment of the call.
**Method**: `getState`
**Endpoint**: N/A (Method call)
**Parameters**:
None
**Request Example**:
```javascript
ref.current?.getState();
```
**Response**:
#### Success Response
- **state** (CropZoomState) - The current transformation state of the component.
#### Response Example
```json
{
"scale": 1.5,
"translateX": 50,
"translateY": 20
}
```
---
### setTransformState
**Description**: Assign the internal transformation values for this component. If the provided state is not achievable within the component's boundaries, it will be approximated to the closest valid state.
**Method**: `setTransformState`
**Endpoint**: N/A (Method call)
**Parameters**:
#### Request Body
- **state** (CropZoomTransformState) - Required - Object describing the transformation values to assign to the CropZoom component.
- **animate** (boolean | undefined) - Optional - Whether to animate the transition or not, defaults to `true`.
**Request Example**:
```javascript
ref.current?.setTransformState({ scale: 2, translateX: 0, translateY: 0 }, false);
```
**Response**:
#### Success Response
None (Operation is asynchronous and side-effect based)
---
### reset
**Description**: Reset all transformations to their initial state.
**Method**: `reset`
**Endpoint**: N/A (Method call)
**Parameters**:
#### Request Body
- **animate** (boolean | undefined) - Optional - Whether to animate the transition or not, defaults to `true`.
**Request Example**:
```javascript
ref.current?.reset(true);
```
**Response**:
#### Success Response
None (Operation is asynchronous and side-effect based)
---
### crop
**Description**: Map all the transformations applied to your component into an object describing the context necessary to perform a crop operation. This object must be used with a library capable of cropping images and/or videos.
**Method**: `crop`
**Endpoint**: N/A (Method call)
**Parameters**:
#### Request Body
- **fixedWidth** (number | undefined) - Optional - Enforce all resulting crops to be of a fixed width. Height is inferred by the computed aspect ratio of CropZoom's `cropSize` property. Calling this with an argument subjects your crops to a one-pixel margin of error, which is intentional to prevent image cropping libraries from crashing your app.
**Request Example**:
```javascript
const cropContext = ref.current?.crop(100);
```
**Response**:
#### Success Response
- **cropContextResult** (CropContextResult) - An object containing the necessary context for cropping.
#### Response Example
```json
{
"x": 10,
"y": 20,
"width": 300,
"height": 200,
"scale": 1.5,
"rotate": 0
}
```
---
### flipHorizontal
**Description**: Flip the component horizontally.
**Method**: `flipHorizontal`
**Endpoint**: N/A (Method call)
**Parameters**:
#### Request Body
- **animate** (boolean | undefined) - Optional - Whether to animate the transition or not, defaults to `true`.
- **cb** (function | undefined) - Optional - Callback to trigger at the beginning of the transition. It receives the angle the component will transition to (0 or 180) as its only argument.
**Request Example**:
```javascript
ref.current?.flipHorizontal(true, (angle) => {
console.log('Flipping to angle:', angle);
});
```
**Response**:
#### Success Response
None (Operation is asynchronous and side-effect based)
```
--------------------------------
### React Native Zoom Toolkit: Pinch Gesture Callbacks
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/resumablezoom.md
Provides details on the callbacks for pinch gestures. `onPinchStart` is triggered when a pinch gesture begins, and `onPinchEnd` is triggered when the gesture concludes. Both callbacks receive pinch gesture event data.
```typescript
// Example usage structure (actual implementation depends on event data usage)
const handlePinchStart = (e: PinchGestureEvent) => {
console.log('Pinch started:', e);
};
const handlePinchEnd = (e: PinchGestureEvent) => {
console.log('Pinch ended:', e);
};
// In your component:
//
```
--------------------------------
### React Native: Image Cropping Logic using Expo Image Manipulator
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/guides/cropzoomexpo.md
Implements the cropping functionality using Expo's `manipulateAsync`. It prepares the necessary actions (resize, flip, rotate, crop) based on the crop reference and then applies them to the image URI. The result is then updated using the `setCrop` function.
```typescript
const crop = async () => {
const result = cropRef.current?.crop();
if (result === undefined) {
return;
}
const actions: Action[] = [];
if (result.resize !== undefined) {
actions.push({ resize: result.resize });
}
if (result.context.flipHorizontal) {
actions.push({ flip: FlipType.Horizontal });
}
if (result.context.flipVertical) {
actions.push({ flip: FlipType.Vertical });
}
if (result.context.rotationAngle !== 0) {
actions.push({ rotate: result.context.rotationAngle });
}
actions.push({ crop: result.crop });
const cropResult = await manipulateAsync(uri, actions);
setCrop(cropResult.uri);
// Add this in case you want to keep testing
setTimeout(() => {
setCrop(undefined);
}, 2500);
};
```
--------------------------------
### Implement Custom Stack Transition in React Native Gallery
Source: https://context7.com/glazzes/react-native-zoom-toolkit/llms.txt
This snippet shows how to create a custom transition for the Gallery component using the stackTransition helper. It defines a customTransition function that calculates opacity and transform styles based on the gallery's state (index, activeIndex, scroll, gallerySize, direction). This allows for unique swipe animations and card-stack effects. The Gallery component is then rendered with this custom transition.
```tsx
import React from 'react';
import { Gallery, stackTransition } from 'react-native-zoom-toolkit';
import type { GalleryTransitionState } from 'react-native-zoom-toolkit';
const CustomGallery = () => {
const images = [
{ id: '1', uri: 'https://example.com/img1.jpg' },
{ id: '2', uri: 'https://example.com/img2.jpg' },
{ id: '3', uri: 'https://example.com/img3.jpg' },
];
const customTransition = (state: GalleryTransitionState) => {
const { index, activeIndex, scroll, gallerySize, direction } = state;
const isHorizontal = direction === 'horizontal';
const size = isHorizontal ? gallerySize.width : gallerySize.height;
const distance = Math.abs(index - activeIndex) * size;
const progress = Math.abs(scroll / distance);
return {
opacity: 1 - progress * 0.5,
transform: [
{ scale: 1 - progress * 0.1 },
{
translateX: isHorizontal
? (index - activeIndex) * gallerySize.width - scroll
: 0,
},
{
translateY: !isHorizontal
? (index - activeIndex) * gallerySize.height - scroll
: 0,
},
],
};
};
const renderItem = (item) => (
);
return (
item.id}
customTransition={customTransition}
vertical={false}
gap={10}
/>
);
};
// Using built-in stack transition
const StackGallery = () => {
const images = [
{ id: '1', uri: 'https://example.com/img1.jpg' },
{ id: '2', uri: 'https://example.com/img2.jpg' },
];
return (
(
)}
customTransition={stackTransition}
/>
);
};
export { CustomGallery, StackGallery };
```
--------------------------------
### Gesture Callbacks
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/snapbackzoom.md
This section details the callback functions that are triggered by specific user gestures like double tap, pinch start/end, and long press.
```APIDOC
## Gesture Callbacks
### onDoubleTap
Callback triggered when the user taps the wrapped component twice.
- **Type**: `(e: TapGestureEvent) => void`
- **Default**: `undefined`
- **Additional Info**: See [tap gesture event data](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/tap-gesture#event-data)
### onPinchStart
Callback triggered when the pinch gesture starts.
- **Type**: `(e: PinchGestureEvent) => void`
- **Default**: `undefined`
- **Additional Info**: See [pinch gesture event data](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/pinch-gesture#event-data)
### onPinchEnd
Callback triggered as soon as the user lifts their fingers off the screen after pinching.
- **Type**: `(e: PinchGestureEvent) => void`
- **Default**: `undefined`
- **Additional Info**: See [pinch gesture event data](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/pinch-gesture#event-data)
### onLongPress
Callback triggered as soon as the long press gesture starts.
- **Type**: `(e: LongPressEvent) => void`
- **Default**: `undefined`
- **Additional Info**: See [long press gesture event data](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/long-press-gesture/#event-data)
```
--------------------------------
### Gesture Event Callbacks
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/cropzoom.md
Provides a set of callback functions that are triggered by various user gesture interactions, including taps, pans, and pinches. These callbacks allow for custom handling of gesture events.
```APIDOC
## Gesture Event Callbacks
### onTap
#### Description
Callback triggered when the user taps the wrapped component once.
#### Type
`(e: TapGestureEvent) => void`
#### Default
`undefined`
#### Additional Info
See [tap gesture event data](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/tap-gesture#event-data)
### onPanStart
#### Description
Callback triggered when the pan gesture starts.
#### Type
`(e: PanGestureEvent) => void`
#### Default
`undefined`
#### Additional Info
See [pan gesture event data](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/pan-gesture#event-data)
### onPanEnd
#### Description
Callback triggered as soon as the user lifts their finger off the screen after a pan gesture.
#### Type
`(e: PanGestureEvent) => void`
#### Default
`undefined`
#### Additional Info
See [pan gesture event data](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/pan-gesture#event-data)
### onPinchStart
#### Description
Callback triggered when the pinch gesture starts.
#### Type
`(e: PinchGestureEvent) => void`
#### Default
`undefined`
#### Additional Info
See [pinch gesture event data](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/pinch-gesture#event-data)
### onPinchEnd
#### Description
Callback triggered as soon as the user lifts their fingers off the screen after a pinch gesture.
#### Type
`(e: PinchGestureEvent) => void`
#### Default
`undefined`
#### Additional Info
See [pinch gesture event data](https://docs.swmansion.com/react-native-gesture-handler/docs/gestures/pinch-gesture#event-data)
```
--------------------------------
### Implement ResumableZoom for Persistent State (React Native)
Source: https://context7.com/glazzes/react-native-zoom-toolkit/llms.txt
Illustrates how to use the ResumableZoom component to maintain zoom and pan states across user interactions, suitable for detail views. It relies on React, 'react-native-zoom-toolkit', 'react-native-reanimated', and 'react-native-gesture-handler'. The component supports programmatic control via a ref and various gesture configuration options.
```tsx
import React, { useRef } from 'react';
import { Image, View, Button } from 'react-native';
import { ResumableZoom } from 'react-native-zoom-toolkit';
import type { ResumableZoomRefType } from 'react-native-zoom-toolkit';
const DetailView = () => {
const zoomRef = useRef(null);
const handleReset = () => {
zoomRef.current?.reset(true);
};
const handleZoomTo = () => {
zoomRef.current?.zoom(3, { x: 100, y: 100 });
};
const handleSwipe = (direction) => {
console.log('Swiped:', direction);
};
const handleUpdate = (state) => {
console.log('Zoom state:', {
scale: state.scale,
containerSize: state.containerSize,
childSize: state.childSize,
maxScale: state.maxScale,
});
};
return (
console.log('Gesture complete')}
>
);
};
export default DetailView;
```
--------------------------------
### Using CropZoom Component in React Native
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/cropzoom.md
Demonstrates the basic usage of the CropZoom component in a React Native application. It utilizes the `useImageResolution` hook to fetch image dimensions and passes necessary props such as `cropSize`, `resolution`, and `OverlayComponent`. The child component (an Image) must have `width: '100%'` and `height: '100%'` styles.
```tsx
import { Image, View, StyleSheet } from 'react-native';
import { CropZoom, useImageResolution, type CropZoomType } from 'react-native-zoom-toolkit`;
const imageUrl = 'url to some image';
const cropSize = { width: 200, height: 200 };
const App = () => {
// A reference so you can access all methods
const ref = useRef(null);
// Utility hook to get the resolution of a network image
const { resolution } = useImageResolution({uri: imageUrl });
// A function that renders an svg with a hole in it.
const renderOverlay = () =>
if(resolution === undefined) {
return null;
}
return (
);
}
export default App;
```
--------------------------------
### Type Definitions
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/resumablezoom.md
Provides definitions for common state structures used within the zoom component, including container and child sizes, scale limits, and transformation values.
```APIDOC
## Type Definitions
### CommonZoomState
Represents the common state of the zoom component.
- **containerSize** (`Size`): Width and height of ResumableZoom.
- **childSize** (`Size`): Width and height of the wrapped component.
- **maxScale** (`number`): Maximum scale allowed by the component.
- **translateX** (`number`): Current translateX transformation value.
- **translateY** (`number`): Current translateY transformation value.
- **scale** (`number`): Current scale transformation value.
### CommonTransformState
Represents common transformation state values.
- **translateX** (`number`): TranslateX transformation value.
- **translateY** (`number`): TranslateY transformation value.
- **scale** (`number`): Scale transformation value.
```
--------------------------------
### CropContextResult Type Definition (TypeScript)
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/cropzoom.md
Defines the structure for crop, context, and resize operations. 'crop' specifies the area and dimensions, 'context' handles rotation and flipping, and 'resize' allows for pre-cropping dimension adjustments. 'resize' is optional and may be undefined.
```typescript
type CropContextResult = {
crop: {
originX: number;
originY: number;
width: number;
height: number;
};
context: {
rotationAngle: number;
flipHorizontal: boolean;
flipVertical: boolean;
};
resize: {
width: number;
height: number;
} | undefined;
};
```
--------------------------------
### React Native: StyleSheet for Image Controls
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/guides/cropzoomexpo.md
Defines the styling for the image manipulation control UI. It includes styles for the root container (layout, positioning) and the crop button (shape, color, alignment).
```typescript
const styles = StyleSheet.create({
root: {
width: '100%',
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'flex-end',
paddingHorizontal: 16,
paddingBottom: 8,
gap: 24,
position: 'absolute',
bottom: 0
},
button: {
width: 50,
height: 50,
borderRadius: 25,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#75DAEA',
},
});
```
--------------------------------
### Handle Pinch Gesture End in React Native
Source: https://github.com/glazzes/react-native-zoom-toolkit/blob/main/docs/docs/components/snapbackzoom.md
The `onPinchEnd` callback is executed as soon as the user lifts their fingers after completing a pinch gesture. It receives a `PinchGestureEvent` object. This requires the React Native Gesture Handler library.
```typescript
function onPinchEnd(e: PinchGestureEvent): void;
```