Animated 可以封裝的 component
- View
- Text
- Image
- ScrollView
import { Animated, Text, View } from 'react-native';
<Animated.View>
</Animated.View>
配置動畫
- Animated.decay() - 以指定的初始速度开始变化,然后变化速度越来越慢直至停下。
- Animated.spring() - 提供了一个简单的弹簧物理模型.
- Animated.timing() - 使用easing 函数让数值随时间动起来。
使用動畫
- start() - 開始
- stop() - 結束
// 開始執行
Animated.timing(
// timing方法使动画值随时间变化
this.state.fadeAnim, // 要变化的动画值
{
toValue: 1, // 最终的动画值
},
).start();
// 結束
Animated.timing(
this.state.posY
).stop();
組合動畫
- parallel - 同時執行
- sequence - 順序執行
Animated.sequence([
// decay, then spring to start and twirl
Animated.decay(position, {
// coast to a stop
velocity: { x: gestureState.vx, y: gestureState.vy }, // velocity from gesture release
deceleration: 0.997
}),
Animated.parallel([
// after decay, in parallel:
Animated.spring(position, {
toValue: { x: 0, y: 0 } // return to start
}),
Animated.timing(twirl, {
// and twirl
toValue: 360
})
])
]).start(); // start the sequence group
插值 - 0, 1 映射到 0, 100
value.interpolate({
inputRange: [0, 1],
outputRange: [0, 100]
});
範例
import React, {Component} from 'react';
import {Animated,Dimensions} from 'react-native';
export default class App extends Component {
state= {
opacity: new Animated.Value(0)
}
componentDidMount() {
Animated.loop(
Animated.sequence([
Animated.timing(this.state.opacity,{
toValue: 1,
duration: 1000,
}),
Animated.timing(this.state.opacity,{
toValue: 0,
duration: 1000,
})
])
).start();
}
render() {
let viewWidth = this.state.opacity.interpolate({
inputRange: [0, 1],
outputRange: [0, Dimensions.get('window').width],
extrapolate: "clamp",
})
return (
<Animated.View style={{flex:1,backgroundColor:'red',opacity:this.state.opacity,width:viewWidth}}></Animated.View>
);
}
}
參考
- React Native Animations 動畫入門
- 官方文件