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

dav*_*esp 1 javascript svg reactjs react-native expo

我有以下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',
  },
});
Run Code Online (Sandbox Code Playgroud)

SVG通过组件显示图像:HomerSvg它使用react-native-svg包。

我需要的是以某种方式调整SVG图像的大小。在上面的代码中,我尝试了但没有成功。

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

您对我如何实现这一目标有任何想法吗?

谢谢!

Jav*_*oya 10

我知道这是一个老问题,但也许我们忘记了这里的基础知识,请记住一些导入的 SVG 可以提供widthheight

import HomeSvg from './assets/HomeSvg';

<HomeSvg height={20} width={20}/>
Run Code Online (Sandbox Code Playgroud)


Yos*_*ger 6

如果没有 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>
Run Code Online (Sandbox Code Playgroud)


小智 1

您可以将所有<Path />元素包装在 a 内,并通过使用设备的宽度和高度计算比例因子来<G />缩放组件。<G />Dimensions

<G transform="scale(scaleFactor) translate(offsetX,offsetY)>
<Path/>
<Path/>
.
.
.
<G/>
Run Code Online (Sandbox Code Playgroud)

其中scaleFactor、offsetX和offsetY可以通过以下方式计算const { height, width } = Dimensions.get("window")

  • 你好,你能举一个更好的例子吗,我正在努力解决这个问题 (2认同)