在React Native中保持全宽图像的纵横比

Par*_*wal 43 react-native

我对标签有疑问.我想要一个图像占据父对象的整个宽度,我使用alignSelf:stretch,但我也希望高度根据图像的纵横比.我怎样才能实现这样的目标?

所以我想要一种方法来指定高度作为图像宽度的比例.

Par*_*wal 37

使用style={{ aspectRatio: 3/2 }}用于与宽度为3高度比水平图像:2.

文档:https://facebook.github.io/react-native/docs/layout-props.html#aspectratio

(适用于RN 0.40+)

  • 美丽的。我与“flex: 1”一起执行此操作,并将容器设置为“flexDirection: 'row'”,并且我能够使图像在保留纵横比的情况下拉伸包含元素的宽度 100%。谢谢。 (2认同)

tom*_*obi 29

我喜欢bdv的方法,我几乎在我的应用程序中使用这种图像.这就是为什么我创建了一个自己的组件,onLayout用于支持设备轮换.

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 (
            <View onLayout={this._onLayout.bind(this)}>
                <Image
                    source={this.props.source}
                    style={{
                        width: this.state.width,
                        height: this.state.height
                    }} />
            </View>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

<FullWidthImage source={{uri: 'http://example.com/image.jpg'}} />
<FullWidthImage source={require('./images/image.jpg')} />
Run Code Online (Sandbox Code Playgroud)

或者,如果您知道这样的比例:

<FullWidthImage source={{uri: 'http://example.com/image.jpg'}} ratio={0.5} />
<FullWidthImage source={require('./images/image.jpg')} ratio={0.5} />
Run Code Online (Sandbox Code Playgroud)

  • 如果Image的源需要是静态图像资源,使用`require`就像`require('../../ some.png')`? (3认同)

小智 26

<Image
   source={require('../../assets/img/headers/image-1.jpg')}
   style={styles.responsiveImage}
 />

const styles = StyleSheet.create({

  responsiveImage: {
    width: '100%',
    // Without height undefined it won't work
    height: undefined,
    // figure out your image aspect ratio
    aspectRatio: 135 / 76,
  },

});
Run Code Online (Sandbox Code Playgroud)

  • `height:undefined` 是最好的秘密。我的意思不是很好。 (8认同)
  • 您可以使用 `height: auto` 来代替更明确 (4认同)
  • 感谢'aspectRatio' 的提示,但我不需要'height: undefined' 就可以了——也许更新已经解决了这个问题? (3认同)

bdv*_*bdv 9

它实际上非常简单.

这个Image班有一个getSize方法.[1]

假设您已为自己创建了一个组件,aspectRatioImage并且每次componentWillMount触发时都会计算出适当的值.

然后你的代码看起来像这样:

componentDidMount() {
    Image.getSize(this.props.source.uri, (srcWidth, srcHeight) => {
      const maxHeight = Dimensions.get('window').height; // or something else
      const maxWidth = Dimensions.get('window').width;

      const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
      this.setState({ width: srcWidth * ratio, height: srcHeight * ratio });
    }, error => {
      console.log('error:', error);
    });
  }
Run Code Online (Sandbox Code Playgroud)

因此,现在图像高度和宽度都保存在组件的状态中,您可以运行

 <Image
   style={{ width: this.state.width, height: this.state.height }}
   source={this.props.source}
   resizeMode="cover"
 />
Run Code Online (Sandbox Code Playgroud)

[1] - https://facebook.github.io/react-native/docs/image.html#getsize


小智 7

就我而言,我还必须将高度设置为“自动”:

{
    width: 200,
    height: 'auto',
    aspectRatio: 16 / 9,
}
Run Code Online (Sandbox Code Playgroud)


ant*_*989 5

通常,执行以下操作会给我们一个根据方向渲染为最大宽度/高度的图像,同时保持图像本身的纵横比:

render(){
    return(<Image style={{'width': Dimensions.get('window').width, 
                         'height': Dimensions.get('window').height}}
                  resizeMode='contain'
                  source='[URL here]'
           </Image>);
}
Run Code Online (Sandbox Code Playgroud)

将 'contain' 与 resizeMode 结合使用:均匀缩放图像(保持图像的长宽比),以便图像的两个尺寸(宽度和高度)等于或小于视图的相应尺寸(减去填充)。

更新: * 不幸的是,似乎 resizeMode 的“包含”存在一个常见错误,特别是在 Android 上使用 React Native 时: https: //github.com/facebook/react-native/pull/5738 *


小智 5

您可以根据宽高比来计算图像高度.

因此,如果图像最初为200x100,则将其resizeMode设置为拉伸:

var deviceWidth: Dimensions.get('window').width;

...

myImage {
    width: deviceWidth,
    height: deviceWidth * 0.5
}
Run Code Online (Sandbox Code Playgroud)

我也许知道这是不是最好的做法,但它帮助了我很多的所有尺寸的图像是需要十个分量与其他图像等有一定关系


Iho*_*nko 5

您可以使用react-native-scalable-image。以下示例将完成这项工作:

import React from 'react';
import { Dimensions } from 'react-native';
import Image from 'react-native-scalable-image';

const image = <Image width={Dimensions.get('window').width} source={{uri: '<image uri>'}} />;
Run Code Online (Sandbox Code Playgroud)