React Native display SVG from a file

前端 未结 3 1500
执念已碎
执念已碎 2020-12-17 18:19

How do I display an SVG image that I require() in React Native.

  • https://github.com/brentvatne/react-native-svgkit Is not under active development
相关标签:
3条回答
  • 2020-12-17 18:40

    Converting to a png is the easiest solution. SVG Images are listed in ProductPains as a pain point and you may upvote it, if you see the need, but for now there is no great out of the box solution for svg images.

    0 讨论(0)
  • 2020-12-17 18:42

    You can display small SVG file as data using this library,

    Note: Large SVG images are not rendering properly.

    npm i react-native-remote-svg

    import Image from 'react-native-remote-svg'
    
    <Image
     source={{
    uri: `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" 
    width="100px" height="100px"  viewBox="0 0 100 100">
         <ellipse data-custom-shape="ellipse" cx="50" cy="50" rx="50" ry="50" 
    fill="green"  stroke="#00FF00" stroke-width ="2" />
       </svg>`
    }}
    style={{ width: 100, height: 100}}
    />
    

    If you want to display any size of images remotely with above library and then do this,

    <Image
      source={{ uri: 'https://example.com/my-pic.svg' }}
      style={{ width: 200, height: 532}}
    />
    

    But if you used this one for display the local svg file, then you will get some issues in android when you bundle and put the release.

    import Image from 'react-native-remote-svg'
    <Image source={require('./image.svg')} />
    

    or you can use Icomoon (For small SVG images/Icons),

    Recommended: Use Icomoon for Icons and Small SVG Images

    See this video to setup the icomoon in react native

    0 讨论(0)
  • 2020-12-17 18:53

    You can hack around this using a webview. I also had to put my SVGs as strings in .js files (which is not good at all). But it works pretty reliably. There is a split second where they show up as white before the SVG loads, but it's good enough for me.

    Roughly something like:

    import React, { View, WebView } from 'react-native'
    import s from 'string'
    
    const firstHtml = '<html><head><style>html, body { margin:0; padding:0; overflow:hidden } svg { position:fixed; top:0; left:0; height:100%; width:100% }</style></head><body>'
    const lastHtml = '</body></html>'
    export default (props) =>
      <View style={props.containerStyle}>
        <WebView
          style={[{ width: 200, height: 100, backgroundColor: props.backgroundColor }, normalizeStyle(props.style)]}
          scrollEnabled={false}
          source={{ html: `${firstHtml}${props.svgContent}${lastHtml}` }}
        />
      </View>
    
    0 讨论(0)
提交回复
热议问题