I am newbie at react-native. What I want to do is that fit an image in device and keep the ratio of image. Simply I want to make width : 100%
I searched how to make it and seems resizeMode = 'contain'
is good for that.
However, since I used resizeMode = 'contain'
, the image keeps the position vertically centered which I don't want. I want it to be vertically top.
I tried to use a plug-in such as react-native-fit-image but no luck.
And I found the reason why the image is not sizing automatically. But still I have no idea how to make it.
So, my question is what is the best way to deal with this situation?
Do I have to manually put width, height
size each images?
I want :
React native test code :
https://snack.expo.io/ry3_W53rW
Eventually what I want to make :
https://jsfiddle.net/hadeath03/mb43awLr/
Thanks.
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.
To fit an Image to the full width of the screen and maintain aspect ratio with React Native, we can set the width to null and the height to the height we want. to set the height of the Image to 300 and the width to null to fit the Image to make the width flexible and maintain aspect ratio.
In react-native, to set the dynamic width and height to a component, we use built-in interface Dimensions. it takes the dimension of a given component and then sets the width and height to its equivalent.
The image is vertically centered, because you added flex: 1
to the style property. Don't add flex: 1, because that will fill the image to its parent, which is not desired in this case.
You should always add a height and width on an image in React Native. In case the image is always the same, you can use Dimensions.get('window').width
to calculate the size the image should be. For example, if the ratio is always 16x9, the height is 9/16th of the width of the image. The width equals device width, so:
const dimensions = Dimensions.get('window'); const imageHeight = Math.round(dimensions.width * 9 / 16); const imageWidth = dimensions.width; return ( <Image style={{ height: imageHeight, width: imageWidth }} /> );
Note: When using an implementation like this, your image will not automatically resize when rotating your device, using split screen, etc. You will have to take care of those actions as well if you support multiple orientations...
In case the ratio is not the same, dynamically change the 9 / 16 by the ratio for each different image. If you don't really bother the image is a little bit cropped, you can use cover mode with a fixed height as well: (https://snack.expo.io/rk_NRnhHb)
<Image resizeMode={'cover'} style={{ width: '100%', height: 200 }} source={{uri: temp}} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With