簡體   English   中英

無法在 React Native 應用程序中調整 SVG 圖像的大小

[英]Cannot resize an SVG image in React Native app

我有以下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',
  },
});

我通過使用react-native-svg包的組件HomerSvg顯示SVG圖像。

我需要以某種方式調整SVG圖像的大小。 在上面的代碼中,我嘗試了但沒有成功。

我嘗試給容器視圖提供一些寬度和高度,但沒有成功。

您對我如何實現這一目標有任何想法嗎?

謝謝!

如果沒有 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>

我知道這是一個老問題,但也許我們忘記了這里的基礎知識,請記住一些導入的 SVG 可以提供widthheight

import HomeSvg from './assets/HomeSvg';

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

您可以將所有<Path />元素包裝在<G />並通過使用Dimensions即設備的寬度和高度)計算比例因子來縮放<G />組件。

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

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

除非 SVG 的尺寸基於容器尺寸,否則它們不會改變。 設置尺寸的圖像會忽略其父尺寸,您可以在 HomerSvg.js 中設置尺寸

希望這可以幫助!

對我來說,問題是 SVG 優化刪除了viewBox
嘗試將viewBox="0 0 width height"屬性添加到Svgwidthheight是原始尺寸)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM