Search code examples
imagereact-nativestylessizecenter

React native image keep centered


I have a simple screen with an image and some text + a button on the bottom of the page. In portrait mode it looks good, but on landscape, the image, the text and the button are not displayed properly. I am trying to make the image to adjust the size when the height is not enough but i cannot find a way to do that.

 render() {        
    return (
        <View style={styles.container}>
            <View style={styles.bodyContainer}>
                <Image style={styles.image}
                    source={require('./../../assets/images/server-info-icon.png')}
                />
                <Text style={styles.serverDetailsText}>Server details</Text>
                <Text style={styles.instructionText}>instruction</Text>
            </View>
            <View style={styles.buttonContainer}>
                <TouchableHighlight style={styles.gotItButton}
                        onPress={() => this.props.navigation.goBack(null)}>
                    <Text style={styles.gotItButtonText}>GOT IT</Text>
                </TouchableHighlight>
            </View>
        </View>
    );
};

const styles = StyleSheet.create({
container: {
    flex: 1,
    backgroundColor: '#ffffff'
},
bodyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
},
buttonContainer: {
    height: 82
},
gotItButton: {
    backgroundColor: COLORS.BUTTONS_COLOR,
    height: 46,
    width: 288,
    borderRadius: 25,
    alignSelf: 'center',
    position: 'absolute',
    bottom: 18
},
gotItButtonText: {
    textAlign: 'center',
    paddingTop: 11,
    paddingBottom: 13,
    fontSize: 17,
    fontFamily: CONSTANTS.DEFAULT_FONT,
    fontWeight: CONSTANTS.TEXT_BOLD_WEIGHT,
    color: COLORS.BUTTONS_TEXT_COLOR
},
image: {
    maxHeight: 170,
    maxWidth: 361,
    marginBottom: 5
},
instructionText: {
    color: COLORS.LABELS_COLOR,
    fontSize: 15,
    fontFamily: CONSTANTS.DEFAULT_FONT,
    height: 36,
    width: 206,
    flexWrap: 'wrap',
    textAlign: 'center',
    marginTop: 2,
    marginBottom: 2
},
serverDetailsText: {
    color: COLORS.TEXT_COLOR,
    fontSize: 17,
    fontFamily: CONSTANTS.DEFAULT_FONT,
    fontWeight: CONSTANTS.TEXT_BOLD_WEIGHT,
    width: 206,
    textAlign: 'center',
    marginTop: 2,
    marginBottom: 2
}

})


Solution

  • Sample Code

    <Image style={{flex: 1,
               width: null,
               height: null}}
               source={require('myimage')}
    />
    

    please add Outer View with style use flex. then Inner Flex Varies to 0.1 to 1.