React-native, how to resize the image based on the original size of image?

senthil balaji picture senthil balaji · Dec 4, 2017 · Viewed 7.3k times · Source

I have list of images to be displayed, wherein size of the image is unknown, how can I display the image fully without any transparent spaces in top and bottom of the image? (I tried getting image size from getSize method, which is eventually giving lot of spaces in top and bottom) I wanted image to resized and fit in like this, I wanted image to resized and fit in like this,

But I'm getting white spaces if I put resize mode to contain, and if I put resize mode to stretch the size of small image is loosing its quality and if I put resize mode to stretch the size of small image is loosing its quality

how can I resize the image so that the white spaces are removed, and fit itself

Answer

senthil balaji picture senthil balaji · Dec 5, 2017
    import React, { Component } from "react";
    import { Dimensions, Image } from "react-native";

    const { width, height } = Dimensions.get("window");

    export default class ResizedImage extends Component {
      constructor(props) {
        super(props);
        this.state = {
          height: 0
        };
      }

      componentDidMount() {
        Image.getSize(
          this.props.source.uri,
          (srcWidth, srcHeight) => {
            const ratio = Math.min(width / srcWidth, height / srcHeight);
            this.setState({ height: srcHeight * ratio });
          },
          error => console.log(error)
        );
      }
      componentWillUnmount() {
        this.setState({ height: 0 });
      }

      render() {
        const { source} = this.props;
        return (
          <Image
            source={{ uri: source.uri }}
            style={{
              width: width * 0.9,
              height: this.state.height
            }}
            resizeMode={"cover"}
          />
        );
      }
    }

You can use this as component and pass the URI as props and everything is done.