manpenaloza
manpenaloza

Reputation: 385

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

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?

Upvotes: 15

Views: 44757

Answers (4)

Hamza Waleed
Hamza Waleed

Reputation: 1462

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'
},

Upvotes: 6

Max Ferreira
Max Ferreira

Reputation: 721

This code worked for me

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

Upvotes: 6

mezod
mezod

Reputation: 2391

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.

Upvotes: 4

LHIOUI
LHIOUI

Reputation: 3337

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

Upvotes: 26

Related Questions