大部分你需要的东西都来自Animated
模块。它包括两个值类型,Value
用于单个的值,而ValueXY
用于向量值;还包括三种动画类型,spring
,decay
,还有timing
,以及三种组件类型,View
,Text
和Image
。你可以使用Animated.createAnimatedComponent
方法来对其它类型的组件创建动画。
这三种动画类型可以用来创建几乎任何你需要的动画曲线,因为它们每一个都可以被自定义:
spring
: 基础的单次弹跳物理模型,符合Origami设计标准
friction
: 摩擦力,默认为7.tension
: 张力,默认40。decay
: 以一个初始速度开始并且逐渐减慢停止。
velocity
: 起始速度,必填参数。deceleration
: 速度衰减比例,默认为0.997。timing
: 从时间范围映射到渐变的值。
duration
: 动画持续的时间(单位是毫秒),默认为500。easing
:一个用于定义曲线的渐变函数。阅读Easing
模块可以找到许多预定义的函数。iOS默认为Easing.inOut(Easing.ease)
。delay
: 在一段时间之后开始动画(单位是毫秒),默认为0。 动画可以通过调用start
方法来开始。start
接受一个回调函数,当动画结束的时候会调用此回调函数。如果动画是因为正常播放完成而结束的,回调函数被调用时的参数为{finished: true}
,但若动画是在结束之前被调用了stop
而结束(可能是被一个手势或者其它的动画打断),它会收到参数{finished: false}
。
多个动画可以通过parallel
(同时执行)、sequence
(顺序执行)、stagger
和delay
来组合使用。它们中的每一个都接受一个要执行的动画数组,并且自动在适当的时候调用start/stop。举个例子:
Animated.sequence([ // 首先执行decay动画,结束后同时执行spring和twirl动画
Animated.decay(position, { // 滑行一段距离后停止
velocity: {x: gestureState.vx, y: gestureState.vy}, // 根据用户的手势设置速度
deceleration: 0.997,
}),
Animated.parallel([ // 在decay之后并行执行:
Animated.spring(position, {
toValue: {x: 0, y: 0} // 返回到起始点开始
}),
Animated.timing(twirl, { // 同时开始旋转
toValue: 360,
}),
]),
]).start(); // 执行这一整套动画序列
默认情况下,如果任何一个动画被停止或中断了,组内所有其它的动画也会被停止。Parallel有一个stopTogether
属性,如果设置为false
,可以禁用自动停止。
这里我们用spring来做缩放效果,以及timing来做若隐若现的渐变效果。第一种:图片先变大后变小的效果。初始化都需要定义 new Animated.Value(0).
export default class Playground extends Component {
constructor(props) {
super(props);
this.state = {
bounceValue: new Animated.Value(0),
};
}
render() {
return (
<Animated.Image // 可选的基本组件类型: Image, Text, View
source={require('../images/1.jpg')}
style={{
width: 100,
height: 100,
margin:50,
transform: [ // `transform`是一个有序数组(动画按顺序执行)
{scale: this.state.bounceValue}, // 将`bounceValue`赋值给 `scale`
]
}}
/>
);
}
componentDidMount() {
this.state.bounceValue.setValue(1.5); // 设置一个较大的初始值
Animated.spring( // 可选的基本动画类型: spring, decay, timing
this.state.bounceValue, // 将`bounceValue`值动画化
{
toValue: 0.8, // 将其值以动画的形式改到一个较小值
friction: 1, // Bouncier spring
}
).start(); // 开始执行动画
}
}
export default class Timing extends Component{
constructor(props){
super(props);
this.state = {
imgOpacity: new Animated.Value(0)
}
}
componentDidMount(){
Animated.timing(
this.state.imgOpacity,{
toValue:1,
duration:3000
}
).start();
}
render(){
return(
<Animated.Image style={{opacity:this.state.imgOpacity,margin:100}}>
<Image source={require('../images/1.jpg')} style={{width:100,height:100}}/>
</Animated.Image>
);
}
}
有任何疑问,可以查看Github源码地址:
https://github.com/SpicyBoiledFish/react-native-Animated-demos