React Native 图像大小调整不会导致宽度改变 [英] React Native image resize does not result in changed width
问题描述
我正在尝试在 React Native 0.53.0
中制作位置图标.我创建了一个位置标记的 png,其大小为 114 x 200.然后,我创建了一个组件,它具有以下渲染方法:
I'm trying to make an location icon in react native 0.53.0
. I created a png of a location marker, which has a size of 114 x 200. Then, I created a component, which has the following render method:
render() {
return (
<Image
source={locationImg}
resizeMode="contain"
style={{ flex: 1 }}
/>
);
}
然后我在高度为 50px
和填充为 5px
的视图中使用这个组件,这意味着图标的高度为 40px代码>.然后我会假设我的图标组件的宽度约为
23px
,但事实并非如此.尽管使用了 resizeMode="contain"
,宽度并没有缩小,而是保持在图像的原始尺寸 114px
.
I then use this component in a View that has a height of 50px
and a padding of 5px
, meaning the icon will have a height of 40px
. I would then assume that the width of my icon component would be about 23px
, but this is not the case. Despite the resizeMode="contain"
, the width does not get scaled down, but stays at the original size of the image, 114px
.
为什么宽度没有缩小,我应该怎么做才能达到我想要的结果?
Why doesn't the width scale down as well, and what should I do differently to achieve my wanted result?
推荐答案
我想出了以下组件:
import React, { Component } from 'react';
import { Image, View } from 'react-native';
import locationImg from '../assets/images/locationImage.png'
// Calculate the ratio to be able to scale the width correctly
const { width: WIDTH, height: HEIGHT } = Image.resolveAssetSource(locationImg);
const RATIO = WIDTH / HEIGHT;
class LocationIcon extends Component {
// Have the desired width of the component in state
state = { width: 0 };
// When receiveing layout, calculate the desired width and update state
onLayout = event => {
const { height } = event.nativeEvent.layout;
this.setState({ width: height * RATIO });
}
render() {
return (
<View>
<Image
source={locationImg}
resizeMode="contain"
onLayout={this.onLayout}
style={{
flex: 1,
width: this.state.width, // Update width from state
}}
/>
</View>
);
}
}
export default LocationIcon;
这篇关于React Native 图像大小调整不会导致宽度改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!