I have a query regarding tag. I want an image to take entire width of parent which I do using alignSelf:stretch, but I also want the height to be according to the aspect ratio of the image. How can I achieve something like this?
So I want a way to specify the height as a ratio of the width of the Image.
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.
By setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained. The end result is an image that scales up or down perfectly.
aspectRatio Aspect ratio controls the size of the undefined dimension of a node. See https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio for more details. On a node with a set width/height, aspect ratio controls the size of the unset dimension.
resizeMode contain : Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding). stretch : Scale width and height independently, This may change the aspect ratio of the src.
Use style={{ aspectRatio: 3/2 }}
for a horizontal image with width to height ratio of 3:2.
Docs: https://reactnative.dev/docs/layout-props#aspectratio
(Available in RN 0.40+)
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