Auto scale image height with React Native

后端 未结 14 1189
陌清茗
陌清茗 2020-12-04 23:19

In my React Native app, I am fetching images from an API with unknown dimensions. How do I auto scale the height if I know my desired width?

Example:

I set t

14条回答
  •  既然无缘
    2020-12-04 23:53

    Try this:

     import React, { Component, PropTypes } from "react";
     import { Image } from "react-native";
    
    export default class ScaledImage extends Component {
    constructor(props) {
        super(props);
        this.state = { source: { uri: this.props.uri } };
    }
    
    componentWillMount() {
        Image.getSize(this.props.uri, (width, height) => {
            if (this.props.width && !this.props.height) {
                this.setState({
                    width: this.props.width,
                    height: height * (this.props.width / width)
                });
            } else if (!this.props.width && this.props.height) {
                this.setState({
                    width: width * (this.props.height / height),
                    height: this.props.height
                });
            } else {
                this.setState({ width: width, height: height });
            }
        });
    }
    
    render() {
        return (
            
        );
    }
    }
    
    ScaledImage.propTypes = {
    uri: PropTypes.string.isRequired,
    width: PropTypes.number,
    height: PropTypes.number
    };
    

    I'm passing the URL as a prop called uri. You can specify your width prop as Dimensions.get('window').width and that should cover it.

    Note that this will also work if you know what you want to set the height to and you need to resize the width to maintain the ratio. In that case, you would specify the height prop instead of the width one.

提交回复
热议问题