[英]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 可以提供width和height 。
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"
属性添加到Svg
( width
和height
是原始尺寸)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.