You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native中创建支持多渐变色彩的80%环形进度条

在React Native中创建多渐变色彩的80%环形进度条

多渐变环形进度条示例

请问如何在React Native中创建如图所示的、支持多渐变色彩的80%环形进度条?


可以借助react-native-svg库实现这类自定义渐变环形进度条,以下是具体实现方案:

1. 安装依赖

首先安装react-native-svg(Expo项目无需额外配置,裸RN项目需按文档完成自动配置):

npm install react-native-svg
# 或
yarn add react-native-svg

2. 自定义进度条组件

创建一个可复用的渐变环形进度条组件:

import React from 'react';
import { View, StyleSheet } from 'react-native';
import Svg, { Circle, Defs, LinearGradient, Stop } from 'react-native-svg';

const GradientRingProgress = ({ progress = 0.8, size = 200, strokeWidth = 20 }) => {
  const radius = (size - strokeWidth) / 2;
  const circumference = 2 * Math.PI * radius;
  // 计算进度条偏移量,实现百分比显示
  const strokeDashoffset = circumference * (1 - progress);

  return (
    <View style={styles.container}>
      <Svg width={size} height={size}>
        {/* 定义多色渐变 */}
        <Defs>
          <LinearGradient id="progressGradient" x1="0%" y1="0%" x2="100%" y2="0%">
            <Stop offset="0%" stopColor="#FF6B6B" />
            <Stop offset="50%" stopColor="#4ECDC4" />
            <Stop offset="100%" stopColor="#45B7D1" />
          </LinearGradient>
        </Defs>
        {/* 灰色背景环 */}
        <Circle
          cx={size / 2}
          cy={size / 2}
          r={radius}
          stroke="#E0E0E0"
          strokeWidth={strokeWidth}
          fill="transparent"
        />
        {/* 渐变进度环 */}
        <Circle
          cx={size / 2}
          cy={size / 2}
          r={radius}
          stroke="url(#progressGradient)"
          strokeWidth={strokeWidth}
          fill="transparent"
          strokeDasharray={circumference}
          strokeDashoffset={strokeDashoffset}
          strokeLinecap="round"
          // 旋转90度,让进度从顶部开始
          transform={`rotate(-90 ${size / 2} ${size / 2})`}
        />
      </Svg>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default GradientRingProgress;

3. 使用组件

在需要展示进度条的地方导入并使用:

import GradientRingProgress from './GradientRingProgress';

// 示例:展示80%进度的渐变环形进度条
<GradientRingProgress progress={0.8} size={200} strokeWidth={20} />

关键细节说明

  • 渐变效果通过LinearGradient和Stop节点定义,可自行修改offset和stopColor调整渐变色彩和分布
  • strokeDasharray和strokeDashoffset配合实现环形进度的百分比控制,progress取值范围0-1
  • strokeLinecap="round"让进度条两端呈现圆角,匹配示例图的视觉效果
  • transform属性将进度环旋转90度,确保进度从顶部开始(默认环形进度从右侧起始)

内容的提问来源于stack exchange,提问作者Faizan Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 14:16:46