Auto scale image height with React Native

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

    Hooks version of @TheJizel answer. I knew the width but wanted the height of the image, so the below worked for me :

        const ScaledImage = props => {
    
        const [width, setWidth] = useState()
        const [height, setHeight] = useState()
        const [imageLoading, setImageLoading] = useState(true)
    
        useEffect(() => {
            Image.getSize(props.uri, (width1, height1) => {
                if (props.width && !props.height) {
                    setWidth(props.width)
                    setHeight(height1 * (props.width / width1))
                } else if (!props.width && props.height) {
                    setWidth(width1 * (props.height / height1))
                    setHeight(props.height)
                } else {
                    setWidth(width1)
                    setHeight(height1)
                }
                setImageLoading(false)
            }, (error) => {
                console.log("ScaledImage,Image.getSize failed with error: ", error)
            })
        }, [])
    
    
        return (
            height ?
                
                    
                
                : imageLoading ?
                    
                    : null
        );
    }
    

    Usage :

    
    

提交回复
热议问题