探索创新图片交互:React Native Image Pan Zoom
import React from 'react';
import { View, StyleSheet, Image } from 'react-native';
import FastImage from 'react-native-fast-image';
import { PanGestureHandler, State } from 'react-native-gesture-handler';
import Animated, { useAnimatedGestureHandler, useAnimatedStyle, withTiming, runOnJS } from 'react-native-reanimated';
export default function ImagePanZoom({ source }) {
const translateX = useSharedValue(0);
const translateY = useSharedValue(0);
const scale = useSharedValue(1);
const panGestureHandler = useAnimatedGestureHandler({
onStart: (_, ctx) => {
ctx.offsetX = 0;
ctx.offsetY = 0;
ctx.scale = scale.value;
},
onActive: (event, ctx) => {
const { translationX, translationY } = event;
translateX.value = ctx.scale * translationX + ctx.offsetX;
translateY.value = ctx.scale * translationY + ctx.offsetY;
},
onEnd: (event, ctx) => {
const { velocityX, velocityY } = event;
runOnJS(setOffset)(translateX, translateY, velocityX, velocityY, scale);
}
});
const imageStyle = useAnimatedStyle(() => ({
transform: [
{ translateX: translateX.value },
{ translateY: translateY.value },
{ scale: scale.value }
]
}));
return (
<View style={styles.container}>
<FastImage style={styles.image} source={source} />
<Animated.View style={[styles.panContainer, imageStyle]}>
<PanGestureHandler onGestureEvent={panGestureHandler}>
<Animated.View style={styles.zoomableImageContainer}>
<FastImage style={styles.zoomableImage} source={source} />
</Animated.View>
</PanGestureHandler>
</Animated.View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
image: {
width: '100%',
aspectRatio: 1,
resizeMode: 'contain'
},
panContainer: {
...StyleSheet.absoluteFillObject,
justifyContent: 'center',
alignItems: 'center'
},
zoomableImageContainer: {
overflow: 'hidden',
borderWidth: 3,
borderColor: 'white'
},
zoomableImage: {
width: '100%',
aspectRatio: 1,
resizeMode: 'contain'
}
});
这个代码示例使用了React Nat
评论已关闭