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

如何将React中带图片的SVG环形进度条适配迁移至React Native

以下是修正后的完整可运行实现,效果和原React版本完全一致:

import React from 'react';
import Svg, {
  Circle,
  Defs,
  G,
  Image,
  LinearGradient,
  Mask,
  Path,
  Stop,
  Text,
} from 'react-native-svg';

function CircularBar({imgSrc, progress, width}) {
  return (
    <Svg viewBox="0 0 200 210" width={width} height={width * 210 / 200}>
      <Defs>
        <Mask id="m1">
          <Circle cx="100" cy="105" r="55" fill="white" />
        </Mask>
        <LinearGradient
          id="lg1"
          gradientTransform="rotate(0) skewX(-20) skewY(-40)">
          <Stop offset="0" stopColor="red" />
          <Stop offset="75%" stopColor="orange" />
        </LinearGradient>
      </Defs>
      <Image mask="url(#m1)" href={imgSrc} width="200" height="200" x="0" y="0" />
      <Path
        pathLength="360"
        d="M100 175 a 75 75 0 1 1 1 0"
        stroke="#778899"
        fill="none"
        strokeWidth="30"
        strokeLinecap="round"
        strokeDasharray="270 360"
        strokeDashoffset="-45"
      />
      <Path
        pathLength="360"
        d="M100 175 a 75 75 0 1 1 1 0"
        stroke="url(#lg1)"
        fill="none"
        strokeWidth="15"
        strokeLinecap="round"
        strokeDasharray={`${progress * 270} 360`}
        strokeDashoffset="-45"
      />
      <G
        transform="translate(100 180)"
        fontSize="16"
        fontFamily="sans-serif"
        fontWeight="bold"
        textAnchor="middle">
        <Text>Overall</Text>
        <Text transform="translate(0 20)">Wellbeing</Text>
      </G>
    </Svg>
  );
}

export default CircularBar;

核心修改点:

  • 修正Svg根节点配置:还原和React端一致的viewBox="0 0 200 210",高度按比例自适应传入的width参数,避免拉伸变形
  • 修复遮罩错误:Mask内的Circle半径从错误的500改回原逻辑的55,保证内部图片裁切为圆形
  • 恢复进度绑定逻辑:第二个Path的strokeDasharray重新绑定${progress * 270} 360,支持外部传入progress动态控制进度
  • 补全Image组件的height、x、y属性,避免react-native-svg下图片渲染位置异常
  • 统一属性命名为react-native-svg要求的小驼峰格式,避免属性不生效

如果使用本地静态图片,将Image的href属性替换为source即可:

<Image mask="url(#m1)" source={require('./本地图片路径.png')} width="200" height="200" x="0" y="0" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:54:01