如何在 React Native 使用 SVG 向量圖檔

問題

  1. React Native 提供的 Image 無法使用 .svg 向量圖檔
  2. Expo 提供的 Svg 需要透過 CircleRectPathClipPathPolygon 自己繪製

解決方法

透過 SVGR 這個工具將 SVG 轉換成 React Native Component,例如:
$ npx svgr@v1.10.0 --native ./logo.svg > LogoSVG.js
會自動產生下列 react-native-svg 可以支援的程式碼:
import React from 'react';
import Svg, { Defs, LinearGradient, Stop, Path } from 'react-native-svg';

const LogoSVG = props => (
  <Svg {...props}>
    <Defs>...</Defs>
    <Path ... />
    <Path ... />
    ...
  </Svg>
);

export default LogoSVG;
直接在 App 使用:
import React from 'react';
import { View } from 'react-native';

import LogoSVG from './LogoSVG';

class App extends React.Component {
  render() {
    return (
      <View>
        <LogoSVG />
      </View>
    );
  }
}

已知問題

如果 SVG 元件沒有 render 出來,可能需要自行給定寬和高,例如:
<LogoSVG width={320} height={240} />
<Stop />offset propTypes 預設 number 是錯誤的,應該是字串,例如:
<!-- 錯誤的 -->
<Stop offset={0.93} stopColor="#000000" />

<!-- 正確的 -->
<Stop offset="93%" stopColor="#000000" /> 
某些 <Path /> 會掉色,要手動添加 fill props,例如:
<Path
  d="..."
  fill="#00aaa5"
/>

參考文章

留言

這個網誌中的熱門文章

COSCUP 2012

Hahow 為什麼沒有 iOS App

swfobject - 網頁輕鬆嵌入Flash