React Native响应图像宽度,而图像的宽高比保持不变

时间:2016-09-03 21:44:16

标签: react-native

我希望React Native Image的宽度为可用屏幕宽度的50%,不会修改图像的宽度:高度比。

任何提示如何解决这个问题?

4 个答案:

答案 0 :(得分:14)

使用调整大小模式cover并将宽度设置为ScreenWidth / 2,您可以使用Dimensions组件

来恢复屏幕宽度
//Get screen width using Dimensions component 
var {width} = Dimensions.get('window');
//....
//In image style 
image:{
   width: width * 0.5
}
//In render function
<Image resizeMode = 'cover' style = {styles.image}/>

编辑添加溢出

//add overflow : visible 
<Image resizeMode = 'cover' style = {[styles.image,{overflow: 'visible'}]}/>

答案 1 :(得分:1)

可以渲染本地图像而无需给出固定的宽度和高度,但是,对于远程图像,必须提供尺寸,因为本机无法在运行时计算它们。 所以,以下对我有用

<View style={styles.thumbContainer}>
      <Image source={{uri: "REMOTE_IMAGE_URI}} style={styles.thumbnail} />
</View>

并应用以下样式。

thumbContainer: {
    width: '100%',
    height: 400,
  },
  thumbnail: {
    flex: 1,
    width: undefined,
    height: undefined,
    resizeMode: 'cover'
  },

答案 2 :(得分:0)

此代码对我有用

        <Image
            style={{width: '100%', height: 100}}
            resizeMode="center"
            source={{}}
        />

答案 3 :(得分:0)

经过验证的答案对我不起作用,但给了我一个好主意。

它可能不起作用,因为我的图像在ScrollView中。

由于图像需要宽度和高度,因此我的解决方案是获取屏幕的宽度和: a)对于图像宽度:将屏幕宽度乘以我要拍摄的屏幕宽度的百分比。 b)对于图像高度:将屏幕宽度乘以屏幕宽度的百分比,我希望我的图像乘以高度/宽度纵横比。

const { width } = Dimensions.get('window');

<Image style={{ width: width * 0.5, height: width * 0.5 * 2.16 }}
       source={require("everydaycheckmobile/images/introduction/5-overviewdark.png")}
/>

效果很好,但是有必要动态定义您希望图像拍摄的宽度屏幕的百分比,以使其在各种方向上都能很好地响应。

相关问题