1 Animated.Value声明了一个 spinValue 变量,传了一个 0 作为初始值
const spinValue = new Animated.Value(0);
2 再创建了一个名为 spin 的方法
类组件: 可以在componentDidMount 里调用
函数组件: 在useEffect()里调用
可以在页面加载之后进行动画
const spin = () => {
spinValue.setValue(0);
Animated.timing(spinValue, {
toValue: 1, // 最终值 为1,这里表示最大旋转 360度
duration: 800,
easing: Easing.linear,
useNativeDriver: true,
}).start(() => spin());
};
3 可以使用interpolate
方法对字符串进行动画处理。interpolate
接受一个值的范围,通常0到1适用于大多数情况,并将它们插入到一个值的范围中(这些值可以是字符串、数字,甚至是返回值的函数)。
您要做的是获取一个现有的动画值,并将其传递给插值函数,如下所示:
// 映射 0-1的值 映射 成 0 - 360 度
const spin1 = spinValue.interpolate({
inputRange: [0, 1], //输入值
outputRange: ['0deg', '360deg'], //输出值
});
// ui 部分
return (
<ImageBackground source={{ uri: backImg }} style={styles.backLoading} resizeMode={'stretch'}>
<View style={styles.loading}>
<MBText style={styles.text}>旋转的loading</MBText>
<Animated.Image style={[styles.icon, { transform: [{ rotate: spin1 }] }]} source={{ uri: icon }} />
</View>
</ImageBackground>
);
};
完整代码 函数组件
const icon = 'https://imagecdn.ymm56.com/ymmfile/static/resource/a3b1a356-c9a1-4a65-aba2-e8c4b52e2e55.png';
const Loading = () => {
const [spinValue, setSpinValue] = useState(new Animated.Value(0));
//旋转方法
const spin = () => {
setSpinValue((value) => {
value.setValue(0);
return value;
});
Animated.timing(spinValue, {
toValue: 1, // 最终值 为1,这里表示最大旋转 360度
duration: 800,
easing: Easing.linear,
useNativeDriver: true,
}).start(() => spin());
};
useEffect(() => {
// first
spin();
return () => {
// second
};
}, []);
// 映射 0-1的值 映射 成 0 - 360 度
const spin1 = spinValue.interpolate({
inputRange: [0, 1], //输入值
outputRange: ['0deg', '360deg'], //输出值
});
return (
<View style={styles.loading}>
<Text> 旋转的loading</Text>
{/* <Image source={{ uri: icon }} style={styles.icon} /> */}
<Animated.Image style={[styles.icon, { transform: [{ rotate: spin1 }] }]} source={{ uri: icon }} />
</View>
);
};
const styles = StyleSheet.create({
loading: {
display: 'flex',
flexDirection: 'row',
marginLeft: autoFix(112),
justifyContent: 'center',
alignItems: 'center',
},
backLoading: {
height: autoFix(120),
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
margin: 10,
},
icon: {
width: autoFix(28),
height: autoFix(28),
},
text: {
fontSize: autoFix(28),
fontWeight: 'bold',
color: '#FF7000',
marginRight: autoFix(8),
},
});
export default Loading;