How can I automatically scale an SVG element within a React Native View?

后端 未结 4 998
隐瞒了意图╮
隐瞒了意图╮ 2021-02-07 01:10

I am trying to put a react-native-svg element inside of a View such that it\'s rendered with a certain, fixed aspect ratio, but then scaled to be as la

4条回答
  •  一个人的身影
    2021-02-07 01:50

    Here is a component that behaves like your images:

    import React from 'react';
    import { View } from 'react-native';
    
    import Svg, { Circle } from 'react-native-svg';
    
    const WrappedSvg = () =>
      (
        
          
            
          
        
      );
    

    In context:

    const WrappedSvgTest = () => (
      
        
          
        
    
        {/* spacer */}
        
    
        
          
        
      
    );
    

    The trick is to wrap the SVG element in a view that preserves its aspect ratio, then set the SVG sizing to 100% width and height.

    I believe there is some complex interaction between the SVG element size and the viewbox size that makes the SVG render smaller than you would expect, or in some cases not render at all. You can avoid this by keeping your tags at a fixed aspect ratio and setting the tags to 100% width and height, so the viewbox aspect ratio always matches the element ratio.

    Be sure to set aspectRatio to viewbox.width / viewbox.height.

提交回复
热议问题