Search code examples
imagereact-nativeresizeflexbox

RN Image resizeMode: 'contain' strange behaviour


I want to get header with picture and title in a row like this: Desired result

with this code:

<View style={{ flex: 1, backgroundColor:'#ccf6c0', flexDirection:'column',}}>
      {/* ======================= HEADER ===================================*/}
      <View style={{flex: 0, flexDirection: 'row', backgroundColor:'#d5d5f7'}}>
         <Image
           source={require('./images/logo.png')}
           style={{resizeMode: 'contain', flex: 1}}
         />
         <View style={{flex: 1, justifyContent: 'center', backgroundColor:'#f7d5d5'}}>
           <Text style={{fontSize: 17, fontWeight:'bold', marginLeft: 7}}>
             Title
           </Text>
         </View>
       </View>
</View>

But I get this output: Wrong result - there is unnecessary space above and below the image.

What I'm missing here to get result desired?

My guess: image has original size of 360x180 (so by default it should be half width of the 768 simulator screen), but Android accepts it as mdpi image and upscales to xhdpi (x2 in both directions), and then uses this upscaled image to calculate container height. And only THEN resizeMode: 'contain' applies (inside new double-height container). Any suggestions?


Solution

  • The only solution which works in this case is to direct use Dimensions in order to calculate and hard set size for image frame before image will be resized:

    ...
    import Image, Dimensions, StyleSheet from 'react-native';
    ...
    const height = Dimensions.get('window').height;
    ...
    const styles = StyleSheet.create({
      imageBox: {
        flex: 1,
        resizeMode: 'contain',
        width: width/2.12,
        height: width/4.24,
      },
      })
    ...
    <Image
       source={require('./images/image.png')}
       style={styles.imageBox}
    />