Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain aspect ratio of image with full width in React Native

Tags:

react-native

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.

like image 539
Param Aggarwal Avatar asked Apr 15 '15 06:04

Param Aggarwal


People also ask

How do I give a full width image in React Native?

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.

How do you maintain the aspect ratio of an image?

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.

What is aspectRatio in React Native?

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.

What is resizeMode in React Native?

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.


1 Answers

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+)

like image 165
Param Aggarwal Avatar answered Sep 22 '22 08:09

Param Aggarwal