Auto scale image height with React Native

后端 未结 14 1174
陌清茗
陌清茗 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:06

    TypeScript version of @TheJizel answer with optional style property and failure callback in Image.getSize:

    import * as React from 'react'
    import {Image} from 'react-native'
    
    interface Props {
        uri: string
        width?: number
        height?: number
        style?
    }
    
    interface State {
        source: {}
        width: number
        height: number
    }
    
    export default class ScaledImage extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                source: {uri: this.props.uri},
                width: 0,
                height: 0,
            }
        }
    
        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})
                }
            }, (error) => {
                console.log("ScaledImage:componentWillMount:Image.getSize failed with error: ", error)
            })
        }
    
        render() {
            return 
        }
    }
    

    Example usage:

    
    

提交回复
热议问题