Shashika Virajh
Shashika Virajh

Reputation: 9487

How to get the react native image to fit to the Image width and height

In the react-native Image I use, I set the width and height according to the dimensions of the screen. Now when I set an image source, the whole image is not displayed. I tried resizeMode and resizeMethod properties, but still it doesn't work properly. How can I achieve this?

import React, { Component } from "react";
import {
  View,
  Text,
  Image,
  Animated,
  ScrollView,
  StyleSheet,
  Dimensions
} from "react-native";

import { PostProfileBar } from "../../component";

const width = Dimensions.get("window").width;
const height = Dimensions.get("window").height / 3;

class SharePostScreen extends Component {
  constructor(props) {
    super(props);

    this.state = {
      profile: {
        avatar:
          "https://img.bleacherreport.net/img/images/photos/003/733/498/hi-res-0579e42e6ee662e306e09bcf17d72dc4_crop_north.jpg?h=533&w=800&q=70&crop_x=center&crop_y=top",
        first_name: "Sarah",
        last_name: "Williams"
      }
    };
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.sharePostWrapper}>
          <ScrollView>
            <PostProfileBar profile={this.state.profile} />
            <Image
              source={{
                uri: "https://pbs.twimg.com/media/DWvRLbBVoAA4CCM.jpg"
              }}
              resizeMode={'cover'}
              style={styles.image}
            />
          </ScrollView>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  sharePostWrapper: {
    flex: 1,
    margin: 5,
    padding: 5,
    borderWidth: 0.5,
    borderColor: 'gray',
  },
  image: {
    marginTop: 4,
    width: width - 20,
    height: height
  }
});

export default SharePostScreen;

Upvotes: 0

Views: 3796

Answers (1)

Pritish Vaidya
Pritish Vaidya

Reputation: 22209

You need to use the Image in the following way

   <Image
    source={{
        uri: "https://pbs.twimg.com/media/DWvRLbBVoAA4CCM.jpg"
    }}
    resizeMode={'stretch'}
    style={styles.image}
/>

the resizeModes that you may require would be cover, stretch, repeat(IOS only)

To display the entire image, aspect ratio needs to be changed for most of the cases, therefore, you may use resizeMode: stretch

Upvotes: 2

Related Questions