如何在 React Native 中居中 SVG?

Dan*_*Dan 5 svg react-native

我正在努力在 React Native 中对齐 SVG。

到目前为止,我有以下内容,但是 SVG 在组件的左上角呈现。我已经为此奋斗了一两个小时。

const Like = () => (
  <View
    style={{
      height: 45,
      width: 45,
      flex: 1,
      borderWidth: 1,
      justifyContent: 'center',
      alignItems: 'center',
    }}>
    <Svg width={45} height={45} viewBox="0 0 25 25">
      <Path
        d="M5.5 11a.344.344 0 0 1-.28-.126l-3.823-4.32c-.016 0-.041-.02-.078-.062-.033-.042-.067-.08-.095-.113L.88 5.902c-.143-.2-.28-.435-.407-.704a4.44 4.44 0 0 1-.323-.853C.05 4.01 0 3.675 0 3.34 0 2.303.256 1.482.774.88 1.273.293 1.997 0 2.944 0c.243 0 .5.05.771.15.274.1.517.235.732.403.2.15.393.318.58.502.17.15.328.31.473.477.142-.167.3-.327.47-.477.187-.184.381-.352.583-.502.215-.168.458-.302.73-.402.271-.1.53-.151.773-.151.944 0 1.669.293 2.17.879.515.603.774 1.424.774 2.461 0 1.038-.466 2.118-1.397 3.24l-3.824 4.294A.351.351 0 0 1 5.5 11"
        fill="#f26aa3"
      />
    </Svg>
  </View>
);
Run Code Online (Sandbox Code Playgroud)

gay*_*dev 3

您可以直接导入图像文件。例子:

import Image from '../assets/image.svg';
Run Code Online (Sandbox Code Playgroud)

图像包装器的样式是

const styles = StyleSheet.create({
  image: {
    alignItems: 'center',
    justifyContent: 'center',
  },
});
Run Code Online (Sandbox Code Playgroud)

作为回报,

<View style={styles.image}>
  <Image width={100} height={100} />
</View>
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您想直接导入 SVG 文件,则需要 `react-native-svg-transformer`。 (2认同)