Maintain aspect ratio of image with full width in React Native

前端 未结 12 1559
终归单人心
终归单人心 2020-12-07 13:02

I have a query regarding tag. I want an image to take entire width of parent which I do using alignSelf:stretch, but I also want the height to be according to the aspect ra

12条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 13:49

    I like bdv's approach and I use this kind of images almost everywhere in my app. That's why I created an own component which is using onLayout to also support device rotation.

    import resolveAssetSource from 'resolveAssetSource';
    import React, {Component} from 'react';
    import {Image, View} from 'react-native';
    
    export default class FullWidthImage extends Component {
        constructor() {
            super();
    
            this.state = {
                width: 0,
                height: 0
            };
        }
    
        _onLayout(event) {
            const containerWidth = event.nativeEvent.layout.width;
    
            if (this.props.ratio) {
                this.setState({
                    width: containerWidth,
                    height: containerWidth * this.props.ratio
                });
            } else if (typeof this.props.source === 'number') {
                const source = resolveAssetSource(this.props.source);
    
                this.setState({
                    width: containerWidth,
                    height: containerWidth * source.height / source.width
                });
            } else if (typeof this.props.source === 'object') {
                Image.getSize(this.props.source.uri, (width, height) => {
                    this.setState({
                        width: containerWidth,
                        height: containerWidth * height / width
                    });
                });
            }
        }
    
        render() {
            return (
                
                    
                
            );
        }
    }

    You can use it like this:

    
    
    

    Or if you know the ratio like this:

    
    
    

提交回复
热议问题