[javascript] Image resizing in React Native

I am trying to resize an image (smaller to fit screen) in my react native app but am unable to do it as it is too big.

Here is the code:

'use strict';

var React = require('react-native');
var {
  StyleSheet,
  Text,
  TextInput,
  View,
  TouchableHighlight,
  ActivityIndicatorIOS,
  Image,
  Component
} = React;

var styles = StyleSheet.create({
  description: {
    marginBottom: 20,
    fontSize: 18,
    textAlign: 'center',
    color: '#656565'
  },
  container: {
    padding: 30,
    marginTop: 65,
    alignItems: 'center'
  },
  flowRight: {
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'stretch'
  },
  buttonText: {
    fontSize: 18,
    color: 'white',
    alignSelf: 'center'
  },
  button: {
    height: 36,
    flex: 1,
    flexDirection: 'row',
    backgroundColor: '#48BBEC',
    borderColor: '#48BBEC',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  },
  searchInput: {
    height: 36,
    padding: 4,
    marginRight: 5,
    flex: 4,
    fontSize: 18,
    borderWidth: 1,
    borderColor: '#48BBEC',
    borderRadius: 8,
    color: '#48BBEC'
  },
  image: {
    width: 200,
    height: 220
  },
});

class SearchPage extends Component {
  render() {
    return (
      <View style={styles.container}>

        <Image source={require('image!rclogo')} style={styles.image}/>

        <Text style={styles.description}>
          Search for RCers!
        </Text>

        <Text style={styles.description}>
          Search
        </Text>

        <View style={styles.flowRight}>
          <TextInput
            style={styles.searchInput}
            placeholder='Search by Batch, Name, Interest...'/>
          <TouchableHighlight style={styles.button}
              underlayColor='#99d9f4'>
            <Text style={styles.buttonText}>Go</Text>
          </TouchableHighlight>
        </View>

        <TouchableHighlight style={styles.button}
            underlayColor='#99d9f4'>
          <Text style={styles.buttonText}>Location</Text>
        </TouchableHighlight>

      </View>
    );
  }
} 

I tried to take it out of the container tag but cannot seem to understand why it will not render properly?

Can this be done with flexbox resizeMode? How do you do it? I can't find any docs on it...

This question is related to javascript reactjs react-native

The answer is


Try this: (for more details click here)

image: { flex: 1, height: undefined, width: undefined, resizeMode: 'contain' }

This worked for me,

image: {
    width: 200,
    height:220,
    resizeMode: 'cover'
}

You can also set your resizeMode: 'contain'. I defined the style for my network images as:

<Image 
   source={{uri:rowData.banner_path}}
   style={{
     width: 80,
     height: 80,
     marginRight: 10,
     marginBottom: 12,
     marginTop: 12}}
/>

If you are using flex, use it in all the components of parent View, else it is redundant with height: 200, width: 220.


**After setting the width and the height of the image then use the resizeMode property by setting it to cover or contain.The following blocks of code translate from normal css to react-native StyleSheet

// In normal css
.image{
   width: 100px;
   height: 100px;
   object-fit: cover;
 }

// in react-native StyleSheet
image:{
   width: 100;
   height: 100;
   resizeMode: "cover";
 }

OR object-fit contain

// In normal css

.image{
   width: 100px;
   height: 100px;
   object-fit: contain;
 }

 // in react-native StyleSheet
image:{
   width: 100;
   height: 100;
   resizeMode: "contain";
 }

image auto fix the View

image: {
    flex: 1,
    width: null,
    height: null,
    resizeMode: 'contain'
}

Here's my solution if you know the aspect ratio, which you can either get from the image metadata or prior knowledge. This fills the whole width of the screen, but that, of course, can be adjusted.

function imageStyle(aspect)
{
    //Include any other style requirements in your returned object.
    return {alignSelf: "stretch", aspectRatio: aspect, resizeMode: 'stretch'}
} 

This looks a bit nicer than contain, and takes less finessing with sizes, and it will adjust the height to maintain the proper aspect ratio so your images don't look skewed. Using contain will preserve the aspect ratio but will scale it to fit your other style requirements, which may drastically shrink the image.


Use Resizemode with 'cover' or 'contain' and set the height and with of the Image.


This worked for me:

image: {
  flex: 1,
  width: 900,
  height: 900,
  resizeMode: 'contain'
}

Just need to make sure that the width and height are bigger than you need as it is limited to what you set.


{ flex: 1, resizeMode: 'contain' } worked for me. I didn't need the aspectRatio


After trying some combinations, I get this working like this:

image: {
    width: null,
    resizeMode: 'contain',
    height: 220
}

Specifically in that order. I hope this can be helpful for someone. (I know that is an old question)


This worked for me:

image: {
    flex: 1,
    aspectRatio: 1.5, 
    resizeMode: 'contain',

  }

aspectRatio is just width/height (my image is 45px wide x 30px high).


Ran into the same problem and was able to tweak the resize mode until I found something I was happy with. Alternative approaches include:

  • Reduce the size of the Static Resource using an image editor
  • Add a transparent border to the static resource using an image editor
  • Use a Network Resource at the expense of UX

To prevent loss of quality while tweaking images consider working with vector graphics so you can experiment with different sizes easily. Inkscape is free tool and works well for this purpose.


In my case I could not set 'width' and 'height' to null because I'm using TypeScript.

The way I fixed it was by setting them to '100%':

backgroundImage: {
    flex: 1,
    width: '100%',
    height: '100%',
    resizeMode: 'cover',        
}

I adjust your answer a bit (shixukai)

image: {
    flex: 1,
    width: 50,
    height: 50,
    resizeMode: 'contain' }

When I set to null, the image wont show at all. I set to certain size like 50


Hey to make your image responsive is simple: here is an article i wrote about it. https://medium.com/@ashirazee/react-native-simple-responsive-images-for-all-screen-sizes-with-flex-69f8a96dbc6f

you can simply do this and it will scale

_x000D_
_x000D_
container: {
    width: 200,
    height: 220
  },// container holding your image 


  image: {
    width: '100%',
    height: '100%',
    resizeMode: cover,
  },
});
_x000D_
_x000D_
_x000D_

this is because the container which holds the image determines the height and width, so by using percentages you will be able to make your image responsive to all screens size.

here is another example:

_x000D_
_x000D_
<View style={{
width: 180,
height: 200,
aspectRatio: 1 * 1.4,
}}>
<Image
source={{uri : item.image.url}}
style={{
resizeMode: ‘cover’,
width: ‘100%’,
height: ‘100%’
}}
/>
</View>
_x000D_
_x000D_
_x000D_


{ flex: 1, height: undefined, width: undefined, resizeMode: 'contain' }

If you are using these attributes in your style prop in the <Image /> and the image is disappeared.

Put your image into a <View> tag. Like this:

<View 
  style={{
      width: '100%',
     height: '30%'
     }}
>
          <Image
            source={require('../logo.png')}
            style={{
              flex: 1,
              height: undefined,
              width: undefined,
              resizeMode: 'contain'
            }}
            resizeMode={'cover'}
          />
</View>

Give your view the width and height you want.


I tried other solutions and I didn't get the result I was looking for. This works for me.

<TouchableOpacity onPress={() => navigation.goBack()} style={{ flex: 1 }}>
        <Image style={{ height: undefined, width: undefined, flex: 1 }}
            source={{ uri: link }} resizeMode="contain"
        />
</TouchableOpacity>

Note I needed to set this as property of image tag than in css.

resizeMode="contain"

Also note that, you need to set flex: 1 on your parent container. For my component, TouchableOpacity is the root of the component.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to react-native

How to resolve the error on 'react-native start' React Native Error: ENOSPC: System limit for number of file watchers reached How to update core-js to core-js@3 dependency? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65 How can I force component to re-render with hooks in React? What is useState() in React? Getting all documents from one collection in Firestore ReactJS: Maximum update depth exceeded error React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH