最终实现的翻转效果:
翻转.2019-03-20 14_28_17.gif
代码:
import React, { Component } from 'react';
import {
StyleSheet,
SafeAreaView,
Text,
View,
Easing,
TouchableOpacity,
Animated
} from 'react-native';
export default class Interpolate extends Component {
constructor(props) {
super(props)
this.state = {
animatedValue: new Animated.Value(0),
color:'red',
text:'正面'
}
this.rotateAnimated = Animated.timing(
this.state.animatedValue,
{
toValue: 1,
duration: 3000,
easing: Easing.in,
}
);
}
_startAnimated() {
this.timer = setTimeout(
() => {
if(this.state.color==='red'){
this.setState({
color:'blue',
text:'反面'
})
}else {
this.setState({
color:'red',
text:'正面'
})
}
},//延时操作
1500 //延时时间
);
this.state.animatedValue.setValue(0);
this.rotateAnimated.start();
}
componentWillUnmount() {
// 如果存在this.timer,则使用clearTimeout清空。
// 如果你使用多个timer,那么用多个变量,或者用个数组来保存引用,然后逐个clear
this.timer && clearTimeout(this.timer);
}
render(){
const rotateY = this.state.animatedValue.interpolate({
inputRange: [0, 0.5,1],
outputRange: ['0deg', '90deg','0deg']
});
return (
<SafeAreaView style={styles.mainStyle}>
<Animated.View
style={{
alignSelf:'center',
marginTop: 10,
width:100,
height:100,
justifyContent:'center',
alignItems:'center',
fontSize: 18,
color: 'white',
backgroundColor:this.state.color,
transform: [
{rotateY:rotateY},
]
}}
>
<Text style={{color:'#fff'}}>
{this.state.text}
</Text>
</Animated.View>
<TouchableOpacity style={styles.touchStyle} onPress={this._startAnimated.bind(this)}>
<Text style={{width:200,height:100,textAlign:'center',lineHeight:100}}>点击开始动画</Text>
</TouchableOpacity>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
mainStyle:{
flex:1
},
touchStyle:{
padding:10,
alignSelf:'flex-end'
}
})
下面解释一下代码:
- Animated是RN提供的实现动画功能的组件,翻转动画就是采用Animated实现的。
- 首先在构造函数constructor的state中,定义了一个 Animated.Value类型的变量
animatedValue。animatedValue被关联到 <Animated.View/>的transform属性上。
(1)Animated提供了四种动画组件类型:View,Text,Image和ScrollView。你也可以用Animated.createAnimatedComponent()创建其他动画组件,如TouchOpacity等,此方法比较少用,一般用View都可以实现。
(2)在React Native通过transform样式的设置来实现组件(包括文字、图像)的变形。包含四种变形样式:
平移(translate):translateX沿x轴方向平移;translateY 沿y轴方向平移
缩放(scale): scaleX 沿x轴方向放大;scaleY 沿Y轴方向放大;scale 沿x、y轴方向都放大
旋转(rotate):rotateX 绕x轴旋转;rotateY 绕y轴旋转;rotateZ:绕z轴旋转; rotate 不指定轴旋转
倾斜 (skew):skewX 沿x轴方向倾斜;skewY 沿Y轴方向倾斜。
(3)interpolate方法使得输入范围映射到不同的output范围上。
代码中的映射关系为:
inputRange: [0, 0.5,1],
outputRange: ['0deg', '90deg','0deg']
想要实现绕Y轴旋转180度的功能,映射关系应为:
inputRange: [0, 1],
outputRange: ['0deg', '180deg']
但是由于旋转180度后,文字也跟着翻转了,所以用先绕Y轴顺时针旋转90度,再逆时针旋转90度实现。 - 点击按钮调用_startAnimated进行动画,animated.value由0变为1的时间为3秒,在1.5秒时,进行内容切换。
参考链接:
http://www.hangge.com/blog/cache/detail_1746.html
https://www.jianshu.com/p/ed451596a4e1
https://www.jianshu.com/p/e3d72e651765
https://leowang721.github.io/2015/08/13/learning/react-native/animation/
https://www.jianshu.com/p/7fd37d8ed138
网友评论