Created
May 22, 2018 10:36
-
-
Save JesusTheHun/460bd29baa0c5c77aa51d2aaa71effa7 to your computer and use it in GitHub Desktop.
linear gradient dynamic start & end values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import {StyleSheet, Text, View, ScrollView, SafeAreaView} from 'react-native'; | |
import {LinearGradient} from "expo"; | |
export default class App extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
gradientYStart: 0, | |
gradientYEnd: 1, | |
color: '#fff', | |
viewLayout: {} | |
}; | |
this.arr = new Array(50).fill(1); | |
} | |
render() { | |
console.warn({x: 0.5, y: this.state.gradientYStart}); | |
return ( | |
<View style={styles.container}> | |
<LinearGradient | |
start={{x: 0.5, y: this.state.gradientYStart}} | |
end={{x: 0.5, y: this.state.gradientYEnd}} | |
// locations={[0,0.5]} | |
colors={[this.state.color, '#192f6a']} | |
style={styles.linearGradient}> | |
<SafeAreaView> | |
<ScrollView | |
style={styles.scrollView} | |
onLayout={(event) => this.registerViewLayout(event.nativeEvent.layout)} | |
onScroll={(event) => this.updateGradient(event.nativeEvent.contentOffset.y)} | |
scrollEventThrottle={1} | |
> | |
{this.arr.map((f, i) => { | |
return <Text key={i} style={styles.text}>{i}</Text> | |
})} | |
</ScrollView> | |
</SafeAreaView> | |
</LinearGradient> | |
</View> | |
); | |
} | |
registerViewLayout(layout) { | |
this.setState({viewLayout: layout}); | |
} | |
updateGradient(scrollY) { | |
let ratio = scrollY / this.state.viewLayout.height; | |
let color = scrollY <= 0 ? '#fff' : '#000'; | |
this.setState({gradientYStart: ratio, gradientYEnd: 1-ratio, color }); | |
} | |
} | |
const styles = StyleSheet.create({ | |
text: { | |
fontSize: 16 | |
}, | |
scrollView: { | |
marginTop: 50, | |
// height: 2000, | |
}, | |
linearGradient: { | |
height: '100%', | |
width: '100%', | |
}, | |
container: { | |
flex: 1, | |
backgroundColor: '#fff', | |
alignItems: 'center', | |
justifyContent: 'center', | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment