Animated Image Zoom in React Native Scroll View
Create a user controlled image zoom / pan with animated zoom reset using the React Native Scroll View component.
In React Native, a ScrollView component used to contain a single image can be used to zoom in on the object by setting the maximumScale and minimumScale props. The ScrollView documentation lists a currentScale property, as well as a scrollTo and onScroll property, but what might not be obvious is how to reset the scale of an image programmatically, especially if you want to animate that transition.
import React, { Component } from 'react'
import { ScrollView, Image, TouchableHighlight} from 'react-native'
export default class ZoomView extends Component {
static defaultProps = {
doAnimateZoomReset: false,
maximumZoomScale: 2,
minimumZoomScale: 1,
zoomHeight: deviceHeight,
zoomWidth: deviceWidth,
}
handleResetZoomScale = (event) => {
this.scrollResponderRef.scrollResponderZoomTo({
x: 0,
y: 0,
width: this.props.zoomWidth,
height: this.props.zoomHeight,
animated: true
})
}
setZoomRef = node => { //the ScrollView has a scrollResponder which allows us to access more methods to control the ScrollView component
if (node) {
this.zoomRef = node
this.scrollResponderRef = this.zoomRef.getScrollResponder()
}
}
render() {
return (
<ScrollView
contentContainerStyle={{ alignItems: 'center', justifyContent: 'center' }} //flexbox styles
centerContent //centers content when zoom is less than scroll view bounds
maximumZoomScale={this.props.maximumZoomScale}
minimumZoomScale={this.props.minimumZoomScale}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
refNode={this.setZoomRef} //helps us get a reference to this ScrollView instance
style={{ overflow: 'hidden' }}
>
<TouchableHighlight
onPress={this.handleResetZoomScale}
>
<Image
source={this.props.source}
/>
</TouchableHighlight>
</ScrollView>
)
}
}
The code above will allow us to click on the image inside the ScrollView to animate a return to normal scale and position.