探索React Native图像查看新境界:动画流畅的Reanimated Image Viewer
import React, { useRef, useState } from 'react';
import { Animated, Image, StyleSheet, View } from 'react-native';
import Reanimated, { useAnimatedScrollHandler } from 'react-native-reanimated';
const { interpolate, useSharedValue, scrollX } = Reanimated;
const ImageViewer = ({ images }) => {
const scrollViewRef = useRef(null);
const scrollXShared = useSharedValue(0);
const handleScroll = useAnimatedScrollHandler(event => {
scrollXShared.value = event.contentOffset.x;
});
const renderImages = () => {
return images.map((image, index) => {
const imageWidth = 300; // 假设图片宽度为300
const key = `image-${index}`;
return (
<Animated.View
key={key}
style={[
styles.imageContainer,
{
width: imageWidth,
transform: [
{
translateX: interpolate(
scrollXShared.value,
[index * imageWidth, (index + 1) * imageWidth],
[-(width / 2), width / 2]
)
}
]
}
]}
>
<Image source={image} style={styles.image} />
</Animated.View>
);
});
};
return (
<View style={styles.container}>
<Animated.ScrollView
ref={scrollViewRef}
horizontal
pagingEnabled
onScroll={handleScroll}
scrollEventThrottle={1}
showsHorizontalScrollIndicator={false}
style={styles.scrollView}
>
{renderImages()}
</Animated.ScrollView>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1
},
scrollView: {
flex: 1
},
imageContainer: {
justifyContent: 'center',
alignItems: 'center'
},
image: {
width: 300,
height: 300
}
});
export default ImageViewer;
这段代码展示了如何使用React Native和Reanimated库创建一个图片查看器,其中图片之间的切换通过平滑的动画进行。代码使用了Animated.ScrollView
和useAnimatedScrollHandler
来处理滚动事件,并且使用interpolate
函数来实现图片之间的平滑过渡效果。这是一个很好的Reanimated和Animated库结合使用的例子。
评论已关闭