Auto scale image height with React Native

后端 未结 14 1194
陌清茗
陌清茗 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-05 00:07

    The proposed solution works, but you have to download image twice, once to determine the size and another to actually show the image, this is a different approach, image is loaded squared initially and resized.

    import React, { Component, } from "react";
    import { Image } from "react-native";
    import PropTypes from 'prop-types'
    
        export default class ScaledImage extends Component {
            state = {}
    
            componentWillMount() {
                const { uri, width, height } = this.props;
                this.setState({ source: { uri }, width: width || height, height: height || width });
            }
    
            render() {
                return (
                     {
                            const { height, width } = value.nativeEvent.source;
                            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 });
                            }
    
                        }}
                        style={{ height: this.state.height, width: this.state.width }}
                    />
                );
            }
        }
    
        ScaledImage.propTypes = {
            uri: PropTypes.string.isRequired,
            width: PropTypes.number,
            height: PropTypes.number
        };
    

提交回复
热议问题