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'}}><Imagesource={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?

3

Best Answer


This may look like a broken api but this is how I solved it on my case:

<Image source={require('./images/logo.png')} resizeMode='contain' style={{flex:1, width: null, height: null}}/>

width and height null looks odd but this way you get rid the static size and adapt the View's size.

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,},})...<Imagesource={require('./images/image.png')}style={styles.imageBox}/>

You can remove the style from your Image component and add a view around it. Then use that view alongside the resizeMode='contain' prop in the Image component to decide the images' size.

e.g:

 <View style={{ height: 200, width: 200, justifyContent: 'center';}}><Image image={source} resizeMode="contain" /></View>