/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React, {useState} from 'react';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
Alert,
TextInput,
Button,
LayoutAnimation,
TouchableOpacity,
Image,
Dimensions,
Animated,
} from 'react-native';
const screenWidth = Dimensions.get('window').width;
const App = () => {
const imageList = [
{
id: 0,
title: '广告1',
image:
'https://img1.baidu.com/it/u=3414420065,1055223949&fm=253&fmt=auto&app=138&f=JPEG?w=731&h=500',
},
{
id: 1,
title: '广告2',
image:
'https://tse3-mm.cn.bing.net/th/id/OIP-C.0vZ2Av6TvdBfmPtuku0yGwHaJ3?w=206&h=275&c=7&r=0&o=5&dpr=2&pid=1.7',
},
{
id: 2,
title: '广告3',
image:
'https://tse2-mm.cn.bing.net/th/id/OIP-C.fBvFwCl6MVnd5ePGpGI92gHaJ4?w=206&h=275&c=7&r=0&o=5&dpr=2&pid=1.7',
},
];
const [page, setPage] = useState(0);
const [XOffset, setXOffset] = useState(new Animated.Value(1.0));
const handleScroll = e => {
let x = e.nativeEvent.contentOffset.x;
let currentPage = Math.floor(x / screenWidth);
setPage(currentPage);
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.scrollView}>
<ScrollView
style={styles.scroll}
horizontal={true}
pagingEnabled={true}
showsHorizontalScrollIndicator={false}
onMomentumScrollEnd={handleScroll}
onScroll={Animated.event([
{nativeEvent: {contentOffset: {x: XOffset}}},
])}>
{imageList.map((item, index) => {
return (
<Animated.Image
style={[
styles.image,
{
opacity: XOffset.interpolate(
{
inputRange: [
(index - 5) * screenWidth,
index * screenWidth,
(index + 5) * screenWidth,
],
outputRange: [0.0, 1.0, 0.0],
}
),
},
]}
source={{uri: item.image}}
key={item.id}
resizeMode={'cover'}
/>
);
})}
</ScrollView>
<View style={styles.indicator}>
{imageList.map(item => {
let style = {};
if (item.id === page) {
style = {color: 'green'};
}
return (
<Text key={item.id} style={[styles.text, style]}>
·
</Text>
);
})}
</View>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
scrollView: {
width: screenWidth,
height: 400,
},
scroll: {
flex: 1,
},
image: {
width: screenWidth,
height: 400,
},
indicator: {
position: 'absolute',
flexDirection: 'row',
bottom: 0,
width: screenWidth,
justifyContent: 'center',
},
text: {
width: 32,
color: 'orange',
fontSize: 32,
fontWeight: '900',
margin: 10,
},
});
export default App;
React Native - 轮播广告组件(Animated)
于 2022-06-03 23:35:13 首次发布