cssreactjsimagereact-nativeimagebackground

react native back ImageBackground centering


I have an image where i try to center some text on it.

For that i use ImageBackground to have child elements of the image.

However the image is being scaled down on small devices, and full size if possible

When i center my text, it gets centered after the whole image ratio ( on a big screen where you can see the whole image, its centered - on small screens its offset because some of the image is cropped to fit.

<ImageBackground style={{ width: wp('50%'), 
                 height: hp('50%'), 
                 resizeMode: 'cover', 
                 justifyContent: 'center', 
                 alignItems: 'center' }}
                 source={require('../assets/images/12.jpg')}>

    // if the full image is showing - it's centered, otherwise not!
    <Text style={{ color: "red" }}>Centered text</Text>

</ImageBackground>

Solution

  • you need to add an extra view to wrap the ImageBackground and add style property justifyContent and alignItems to center and I think this will erase your problem.

    <View style={{ flex:1 , justifyContent: 'center', alignItems: 'center' }}>
        <ImageBackground
    
            style={{ width: wp('50%'), height: hp('50%'), resizeMode: 'cover', justifyContent: 'center', alignItems: 'center' }}
            source={require('../assets/images/12.jpg')}>
    
            // if the full image is showing - it's centered, otherwise not!
            <Text style={{ color: "red" }}>Centered text</Text>
    
        </ImageBackground>
    </View>