Roo
Roo

Reputation: 613

Full width image containing the image ratio is not stretched in React-Native

I'm trying to add an image that is always 100% width but height is stretched containing the ratio of the image.

I'm adding the image in container:

 <View style={styles.imageContainer}>
     <Image style={styles.image} source={require('../../assets/images/image.png')}/>
 </View>

And changing the resize mode to 'contain':

const styles = StyleSheet.create({
    imageContainer: {
        flex: 1,
    },

    image: {
        width: '100%',
        resizeMode: 'contain',
        backgroundColor: 'red',
    }
}

enter image description here

Image background shows that the image is 100% width (red background) but the source is not stretched. What is the proper way to achieve the result below?

enter image description here

Upvotes: 0

Views: 766

Answers (2)

LordKiz
LordKiz

Reputation: 643

Try:

import {Dimensions} from 'react-native';

const deviceWidth = Dimensions.get('window').width;

.............
.............

const styles = StyleSheet.create({

    image: {
        ....
        width: deviceWidth,
        resizeMode: 'stretch',
        .....
    }
}

Upvotes: 1

user7319004
user7319004

Reputation:

You can start by importing this library:

import Dimensions from 'react-native';

Then you define globally:

const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;

The proper way to write your code is:

const styles = StyleSheet.create({
    imageContainer: {
        flex: 1,
        height: height,
    },

    image: {
        width: width,
        resizeMode: 'contain',
        backgroundColor: 'red',
    }
}

Upvotes: 0

Related Questions