React Native responsive image width while width/height ratio of image keeps the same

后端 未结 4 1492
伪装坚强ぢ
伪装坚强ぢ 2021-02-14 14:35

I want a React Native Image to have a width of 50% of the available screen-width, no modification to width:height ratio of the image.

Any hints how to solve this?

相关标签:
4条回答
  • 2021-02-14 15:35

    The verified answer didn't work for me but gave me a good idea.

    It probably didn't work because my images are within a ScrollView.

    Since images require a width and a height, my solution has been to get the width of the screen and: a) For image width: multiply screen width by % of the screen width I want my image to take. b) For image height: multiply screen width by % of the screen width I want my image to take by height/width aspect ratio.

    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")}
    />
    

    Works nicely, but it will be necessary to dynamically define the % of width screen you want the image to take to make it work good responsively and for various orientations.

    0 讨论(0)
  • 2021-02-14 15:38

    Use resize mode cover and set the width to ScreenWidth / 2 you can retrive the screen width using Dimensions component

    //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}/>
    

    Edit adding overflow

    //add overflow : visible 
    <Image resizeMode = 'cover' style = {[styles.image,{overflow: 'visible'}]}/>
    
    0 讨论(0)
  • 2021-02-14 15:41

    Local images can be rendered without giving a fixed width and height but, for remote images you must provide dimensions as react-native cant calculate them on runtime. So, the following works for me

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

    and apply following styles.

    thumbContainer: {
        width: '100%',
        height: 400,
      },
      thumbnail: {
        flex: 1,
        width: undefined,
        height: undefined,
        resizeMode: 'cover'
      },
    
    0 讨论(0)
  • 2021-02-14 15:42

    This code worked for me

            <Image
                style={{width: '100%', height: 100}}
                resizeMode={'center'}
                source={{}}
            />
    
    0 讨论(0)
提交回复
热议问题