React Native: Simple responsive Images for all screen sizes with flex.
TrackMyStories
Posted on February 20, 2021
Smartphones come in different shapes and sizes, therefore it is paramount our content responds accordingly.
Images can be problematic when delivering our design across different screens. A one size fits all strategy would not work in today's diverse smartphone landscape and would likely result in a user experience nightmare.
The Flexbox module is based on the Cartesian coordinate system, which is distances over two lines running perpendicular, famously known as the
X-axis and Y-axis, with the Cartesian system in mind our container can be calculated with the main axis which runs horizontal, and the cross-axis which runs vertically as illustrated in the image above.
Consider your container as the X-Axis and Y-Axis that holds the Image.
Consider your container as the X-Axis and Y-Axis that holds the Image.
for example:
<View style={styles.container}> // X & Y axis.
<Image /> // value or items{% raw %}`
</View>
```
The container value has a height and width as per your requirements.
for example:
```
container : {width: 180, height: 200}
```
In order to ensure images inside the container adapt to change, we can use percentages to ensure the size is always on par with the height and width of the container.
Therefore, to make the images responsive we can simply set the value of height and width to 100% and resize mode to cover.
```
<View style={{
width: 180,
height: 200,
aspectRatio: 1 * 1.4,
}}>
<Image
source={{uri : item.image.url}}
style={{
resizeMode: ‘cover’,
width: ‘100%’,
height: ‘100%’
}}
/>
</View>
```
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. It will uniformly scale the image whilst maintaining it’s aspect ratio proportionate to the dimensions of the container.
To conclude, the application of geometry can be an effective resource in scalability. The simple notion of a box and the compatibility of its contents is a good way to think about how responsiveness works in our applications. It is important to note that the container’s style has precedence over the image’s style similar to a waterfall effect, that is how the container’s value dictates how high or wide the image can stretch in the UI.
Posted on February 20, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024
November 29, 2024
November 29, 2024
November 28, 2024