發表文章

目前顯示的是 4月, 2018的文章

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

圖片
問題 React Native 提供的 Image 無法使用 .svg 向量圖檔 Expo 提供的 Svg 需要透過 Circle 、 Rect 、 Path 、 ClipPath 和 Polygon 自己繪製 解決方法 透過 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 是錯誤的,應該是字串,例如