无法在 React Native 应用程序中调整 SVG 图像的大小

问题描述 投票:0回答:5

我有以下

React Native
项目:

https://snack.expo.io/BkBU8fAlV

我有以下代码:

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

import HomerSvg from './assets/HomerSvg';

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>
          Change code in the editor and watch it change on your phone! Save to get a shareable url.
        </Text>
        <View style={{ width: 80, height: 80 }}>
          <HomerSvg />
        </View>
        <Card>
          <AssetExample />
        </Card>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

我通过组件显示

SVG
图像:
HomerSvg
,它使用
react-native-svg
包。

我需要的是以某种方式调整

SVG
图像的大小。在上面的代码中我尝试了但没有成功。

我尝试给容器视图一些宽度和高度,但没有成功。

你知道我该如何实现这一目标吗?

谢谢!

javascript reactjs react-native svg expo
5个回答
12
投票

这实际上很容易解决,无需 React Native,只需 SVG 本身即可。

只需将

preserveAspectRatio
标签设置为
none

示例:

<Svg
  width={this.props.width}
  height={this.heights.h1}
  xmlns="http://www.w3.org/2000/svg" 
  viewBox="0 0 750 352"
  preserveAspectRatio="none">
...
</Svg>

11
投票

我知道这是一个老问题,但也许我们忘记了这里的基本原理,请记住 可以为导入的 SVG 提供宽度高度

import HomeSvg from './assets/HomeSvg';

<HomeSvg height={20} width={20}/>

3
投票

对我来说,问题是 SVG 优化被删除了

viewBox

尝试将
viewBox="0 0 width height"
道具添加到
Svg
width
height
是原始尺寸)。


1
投票

您可以将所有

<Path />
元素包装在
<G />
内,并通过使用
<G />
(即设备的宽度和高度)计算比例因子来缩放
Dimensions
组件。

<G transform="scale(scaleFactor) translate(offsetX,offsetY)>
<Path/>
<Path/>
.
.
.
<G/>

其中scaleFactor、offsetX和offsetY可以通过

const { height, width } = Dimensions.get("window")

计算

0
投票

除非 SVG 的尺寸基于容器尺寸,否则它们不会改变。具有设置尺寸的图像会忽略其父级的尺寸,并且您可以在 HomerSvg.js 中设置尺寸

希望这有帮助!

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.