Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

react-native

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?

like image 991
manpenaloza Avatar asked Sep 03 '16 21:09

manpenaloza


People also ask

How do you maintain the aspect ratio of an image in React?

Doing it the React way * using JavaScript division syntax. So, to get a 16:9 ratio, * simply pass `ratio={16/9}`. * width / height, so we need to invert it.

How do I set the width and height of a responsive image?

To make an image responsive, you need to give a new value to its width property. Then the height of the image will adjust itself automatically. The important thing to know is that you should always use relative units for the width property like percentage, rather than absolute ones like pixels.

How do you set image width to be 100 and height to be auto In react-native?

So all we need to do is create a View with width: "100%" , then use onLayout to get the width of that view (i.e. the container width), then use that container width to calculate the height of our image appropriately.

How do I make an image responsive in react-native?

Therefore, to make the images responsive we can simply set the value of height and width to 100% and resize mode to cover. By setting the Image's height and width to 100% and resize mode to cover, the image will proportionately occupy a 100% of the container's real estate inside of the X and Y-Axis or the container.


2 Answers

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'
  },
like image 197
Hamza Waleed Avatar answered Oct 20 '22 05:10

Hamza Waleed


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'}]}/>
like image 29
LHIOUI Avatar answered Oct 20 '22 04:10

LHIOUI