React Native旋转手势实现:如何让圆形顺时针/逆时针旋转?
React Native 实现圆形顺时针/逆时针旋转动画
React Native 里实现旋转动画核心依赖 Animated 库,下面直接给你可运行的示例和关键逻辑说明:
核心逻辑
旋转动画本质是通过修改组件的transform.rotate属性,结合Animated的插值和循环方法实现:
- 顺时针:角度从
0deg过渡到360deg - 逆时针:角度从
360deg过渡到0deg
完整代码示例
import React, { useRef, useEffect } from 'react'; import { View, Animated, StyleSheet } from 'react-native'; const RotatingCircle = () => { // 初始化动画进度值,初始为0 const rotateAnim = useRef(new Animated.Value(0)).current; useEffect(() => { // 顺时针循环动画配置 const clockwiseAnim = Animated.loop( Animated.timing(rotateAnim, { toValue: 1, duration: 2000, // 旋转一圈的时长,单位毫秒 useNativeDriver: true, // 启用原生驱动提升流畅度 }) ); // 逆时针动画配置(需要时替换上面的clockwiseAnim即可) // const counterClockwiseAnim = Animated.loop( // Animated.timing(rotateAnim, { // toValue: 1, // duration: 2000, // useNativeDriver: true, // }) // ); clockwiseAnim.start(); // counterClockwiseAnim.start(); // 组件卸载时停止动画 return () => { clockwiseAnim.stop(); // counterClockwiseAnim?.stop(); }; }, [rotateAnim]); // 插值生成顺时针旋转角度 const clockwiseRotate = rotateAnim.interpolate({ inputRange: [0, 1], outputRange: ['0deg', '360deg'], }); // 插值生成逆时针旋转角度 const counterClockwiseRotate = rotateAnim.interpolate({ inputRange: [0, 1], outputRange: ['360deg', '0deg'], }); return ( <View style={styles.container}> {/* 顺时针旋转的圆形 */} <Animated.View style={[ styles.circle, { transform: [{ rotate: clockwiseRotate }] }, ]} /> {/* 逆时针旋转的圆形(取消注释即可显示) */} {/* <Animated.View style={[ styles.circle, styles.secondCircle, { transform: [{ rotate: counterClockwiseRotate }] }, ]} /> */} </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', gap: 20, }, circle: { width: 100, height: 100, borderRadius: 50, backgroundColor: '#2196F3', }, secondCircle: { backgroundColor: '#F44336', }, }); export default RotatingCircle;
关键部分解释
- Animated.Value:存储动画的进度值(0到1),是动画的核心数据源。
- interpolate:把0-1的进度值映射为实际旋转角度,切换方向只需要反转
outputRange的数值即可。 - Animated.loop:让动画无限循环执行,若只需单次旋转,去掉
loop包裹即可。 - useNativeDriver: true:将动画交给原生线程处理,避免JS线程阻塞,提升动画流畅度。
内容的提问来源于stack exchange,提问作者jksq
相关产品推荐
相关产品推荐

