Skip to content

Instantly share code, notes, and snippets.

@tpraxl
Created December 28, 2017 18:22
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpraxl/02dc4bfcfa301340d26a0bf2140cd8b9 to your computer and use it in GitHub Desktop.
Save tpraxl/02dc4bfcfa301340d26a0bf2140cd8b9 to your computer and use it in GitHub Desktop.
React Native: Simple Responsive Image
// There are many complicated solutions out there.
// In fact, it's pretty easy to autoscale an image if you know the original dimensions.
// Otherwise, see Image.getSize. It should be easy to create a custom component that
// leverages Image.getSize to use this technique
//
import React, { Component } from 'react';
import { StyleSheet, Image, View } from 'react-native';
… // inside render()
<View style={styles.responsiveContainer}>
<Image source={require('../assets/img/logo.png')} style={styles.responsiveImg} />
</View>
… // styles
const styles = StyleSheet.create {
responsiveContainer: {
flex: 1,
// arbitrary width that shall not be exceeded
width: '60%',
// demonstrate the dimensions of the container
backgroundColor: '#00f',
},
responsiveImg: {
// Image dimensions are known: 600, 330
aspectRatio: (600 / 330),
// Make sure the image stretches and shrinks
width: '100%',
height: '100%',
// Make sure the image doesn't exceed it's original size
// If you want it to exceed it's original size, then
// don't use maxWidth / maxHeight or set their
// value to null
maxWidth: 600,
maxHeight: 330,
// center horizontally
marginLeft: 'auto',
marginRight: 'auto',
// make sure, the image is resized properly:
resizeMode: 'contain',
// demonstrate the dimensions of the image
backgroundColor: '#ff0',
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment