React Native自定义圆形加载Spinner实现求助
React Native 自定义圆形加载Spinner实现方案
要实现你想要的圆形Spinner效果,我们可以结合react-native-svg绘制图形,搭配react-native-reanimated实现流畅动画,步骤如下:
1. 安装依赖
首先安装所需的两个库:
npm install react-native-svg react-native-reanimated # 或使用 yarn yarn add react-native-svg react-native-reanimated
2. 实现自定义Spinner组件
下面是完整的组件代码,完美匹配你想要的旋转+描边动画效果:
import React, { useEffect } from 'react'; import { View } from 'react-native'; import Svg, { Circle } from 'react-native-svg'; import Animated, { useSharedValue, useAnimatedProps, withRepeat, withTiming, } from 'react-native-reanimated'; // 创建可动画的Circle组件 const AnimatedCircle = Animated.createAnimatedComponent(Circle); const CustomSpinner = ({ size = 80, color = '#165DFF', strokeWidth = 6 }) => { // 旋转动画值 const rotation = useSharedValue(0); // 描边偏移动画值,控制圆弧显示长度 const strokeDashOffset = useSharedValue(0); // 圆的半径(减去描边宽度的一半,避免超出SVG容器) const radius = (size / 2) - (strokeWidth / 2); // 圆的周长,用于计算描边数组 const circumference = 2 * Math.PI * radius; useEffect(() => { // 启动旋转动画:无限循环,1秒转360度 rotation.value = withRepeat( withTiming(360, { duration: 1000 }), -1, false ); // 启动描边偏移动画:无限循环,反向重复,实现圆弧"收缩-展开"效果 strokeDashOffset.value = withRepeat( withTiming(circumference * 0.6, { duration: 1000 }), -1, true ); }, []); // 绑定动画属性 const animatedProps = useAnimatedProps(() => ({ transform: [{ rotate: `${rotation.value}deg` }], strokeDashoffset: strokeDashOffset.value, })); return ( <View> <Svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}> <AnimatedCircle cx={size / 2} cy={size / 2} r={radius} fill="none" stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" // 描边数组:显示一段圆弧,隐藏剩余部分 strokeDasharray={circumference} animatedProps={animatedProps} /> </Svg> </View> ); }; export default CustomSpinner;
3. 使用组件
在你的页面中直接导入并使用:
import CustomSpinner from './CustomSpinner'; // 在渲染函数中 <CustomSpinner size={100} color="#FF6B6B" strokeWidth={8} />
关键代码说明
- SVG绘制:通过
Circle绘制圆形路径,设置fill="none"只显示描边,strokeLinecap="round"让圆弧两端更圆润。 - 旋转动画:利用
rotation值控制圆形的旋转角度,通过withRepeat实现无限循环。 - 描边动画:通过
strokeDashoffset改变描边的起始位置,配合strokeDasharray实现圆弧长度的动态变化,模拟"呼吸"效果。
内容的提问来源于stack exchange,提问作者Madhu Paka
相关产品推荐
相关产品推荐

