【问题标题】:Cannot resize an SVG image in React Native app无法在 React Native 应用程序中调整 SVG 图像的大小
【发布时间】:2018-12-24 08:23:18
【问题描述】:

我有以下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 图像的大小。上面的代码我试了一下,没有成功。

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

您知道我该如何实现吗?

谢谢!

【问题讨论】:

  • Resize 适用于您已经应用的宽度和高度,您能解释一下吗?
  • 你能显示你解析的代码吗?

标签: javascript reactjs react-native svg expo


【解决方案1】:

这实际上很容易解决,不用 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>

【讨论】:

    【解决方案2】:

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

    import HomeSvg from './assets/HomeSvg';
    
    <HomeSvg height={20} width={20}/>
    

    【讨论】:

      【解决方案3】:

      您可以将所有&lt;Path /&gt; 元素包装在&lt;G /&gt; 中,并通过使用Dimensions 计算比例因子(即设备的宽度和高度)来缩放&lt;G /&gt; 组件。

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

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

      【讨论】:

      • 嗨,你能举个更好的例子吗,我正在努力解决这个问题
      • G从何而来?
      【解决方案4】:

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

      希望这会有所帮助!

      【讨论】:

        【解决方案5】:

        对我来说,问题在于 SVG 优化被删除了 viewBox
        尝试将 viewBox="0 0 width height" 属性添加到 Svgwidthheight 是原始尺寸)。

        【讨论】:

          猜你喜欢
          • 2015-06-11
          • 2019-12-12
          • 1970-01-01
          • 2021-09-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-11
          • 2011-04-29
          相关资源
          最近更新 更多