React Native SVG 使用指南:从基础到高级应用

React Native SVG 使用指南:从基础到高级应用

react-native-svg react-native-svg 项目地址: https://gitcode.com/gh_mirrors/rea/react-native-svg

一、React Native SVG 简介

React Native SVG 是一个强大的库,它允许开发者在 React Native 应用中渲染 SVG 图形。SVG(可缩放矢量图形)是一种基于 XML 的矢量图像格式,具有无损缩放、文件体积小等优势。通过这个库,开发者可以直接在 React Native 中使用 SVG 的各种元素和属性,创建丰富的矢量图形界面。

二、基础使用

1. 基本组件导入

首先需要导入 SVG 相关组件:

import Svg, {
  Circle,
  Rect,
  Path,
  // 其他SVG元素...
} from 'react-native-svg';

2. 简单示例

以下是一个绘制圆形和矩形的示例:

import React from 'react';
import { View } from 'react-native';
import Svg, { Circle, Rect } from 'react-native-svg';

const SvgExample = () => (
  <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
    <Svg height="50%" width="50%" viewBox="0 0 100 100">
      <Circle cx="50" cy="50" r="45" stroke="blue" strokeWidth="2.5" fill="green" />
      <Rect x="15" y="15" width="70" height="70" stroke="red" strokeWidth="2" fill="yellow" />
    </Svg>
  </View>
);

export default SvgExample;

代码解析

  • Svg 是根容器,定义了画布大小和视口
  • Circle 绘制圆形,cx/cy 定义圆心,r 定义半径
  • Rect 绘制矩形,x/y 定义左上角位置,width/height 定义尺寸

三、加载远程SVG资源

1. 基本远程加载

import { SvgUri } from 'react-native-svg';

const RemoteSvg = () => (
  <SvgUri
    width="100%"
    height="100%"
    uri="http://example.com/path/to/image.svg"
  />
);

2. 带CSS样式的远程SVG

如果SVG包含<style>标签,需要使用SvgCssUri

import { SvgCssUri } from 'react-native-svg/css';

const SvgWithCss = () => (
  <SvgCssUri
    width="100"
    height="100"
    uri="https://example.com/styled-svg.svg"
  />
);

3. 错误处理

const SvgWithFallback = () => {
  const [uri, setUri] = React.useState('https://example.com/missing.svg');
  
  return (
    <SvgUri
      width="100%"
      height="100%"
      uri={uri}
      onError={() => setUri('https://example.com/fallback.svg')}
      fallback={<Text>加载失败</Text>}
    />
  );
};

四、本地SVG文件处理

1. 使用SVG转换器

推荐使用react-native-svg-transformer将SVG文件转换为React组件:

// metro.config.js
const { getDefaultConfig } = require('metro-config');

module.exports = (async () => {
  const {
    resolver: { sourceExts, assetExts },
  } = await getDefaultConfig();
  
  return {
    transformer: {
      babelTransformerPath: require.resolve('react-native-svg-transformer'),
    },
    resolver: {
      assetExts: assetExts.filter(ext => ext !== 'svg'),
      sourceExts: [...sourceExts, 'svg'],
    },
  };
})();

2. 使用转换后的SVG

import Logo from './assets/logo.svg';

const App = () => (
  <Logo width={120} height={40} />
);

五、直接使用SVG字符串

1. 基本XML字符串

import { SvgXml } from 'react-native-svg';

const xml = `
  <svg width="32" height="32">
    <circle cx="16" cy="16" r="16" fill="red"/>
  </svg>
`;

const XmlSvg = () => <SvgXml xml={xml} width="100%" height="100%" />;

2. 带CSS的XML字符串

import { SvgCss } from 'react-native-svg';

const cssXml = `
  <svg width="32" height="32">
    <style>.shape { fill: blue; }</style>
    <rect class="shape" width="32" height="32"/>
  </svg>
`;

const CssSvg = () => <SvgCss xml={cssXml} width="100%" height="100%" />;

六、SVG元素详解

1. 公共属性

| 属性 | 默认值 | 说明 | |---------------|-------|-----------------------------| | fill | '#000' | 填充颜色 | | fillOpacity | 1 | 填充不透明度 | | stroke | 'none' | 描边颜色 | | strokeWidth | 1 | 描边宽度 | | strokeOpacity | 1 | 描边不透明度 | | x | 0 | X轴平移 | | y | 0 | Y轴平移 | | rotation | 0 | 旋转角度 | | scale | 1 | 缩放比例 |

2. 常用SVG元素

Circle 圆形
<Circle cx="50" cy="50" r="40" fill="red"/>
Rect 矩形
<Rect x="10" y="10" width="80" height="60" fill="blue"/>
Path 路径
<Path d="M10 80 C 40 10, 65 10, 95 80" stroke="black"/>
Text 文本
<Text x="50" y="50" textAnchor="middle" fill="white">Hello</Text>

七、高级技巧

1. 继承属性

在Svg元素上设置的属性会被子元素继承:

<Svg fill="blue" stroke="red" color="green">
  <Rect width="100" height="100"/> {/* 继承fill和stroke */}
  <Path stroke="currentColor"/> {/* 使用color定义的绿色 */}
</Svg>

2. 渐变效果

<Svg width="100" height="100">
  <Defs>
    <LinearGradient id="grad" x1="0" y1="0" x2="100%" y2="0">
      <Stop offset="0" stopColor="red"/>
      <Stop offset="1" stopColor="blue"/>
    </LinearGradient>
  </Defs>
  <Rect x="0" y="0" width="100" height="100" fill="url(#grad)"/>
</Svg>

八、性能优化建议

  1. 对于静态SVG,优先使用本地文件转换方案
  2. 复杂SVG考虑拆分为多个小组件
  3. 远程SVG添加缓存机制
  4. 使用shouldComponentUpdate避免不必要的重绘

通过本指南,您应该已经掌握了React Native SVG的核心用法。从基本图形绘制到高级特性应用,SVG为React Native应用提供了强大的矢量图形支持。

react-native-svg react-native-svg 项目地址: https://gitcode.com/gh_mirrors/rea/react-native-svg

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蔡怀权

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值