如何设置图像宽度为100%,高度为自动反应原生?

Pra*_*hat 39 javascript image reactjs react-native

我试图在滚动视图中显示图像列表.宽度应为100%,而高度应为自动,保持纵横比.

我做的搜索指向了提供全屏背景风格的各种解决方案.

const styles = StyleSheet.create({
    image: {
        width: null,
        height: 300,
        resizeMode: 'cover'
    }
});

<ScrollView style={{flex: 1}}>
    <Image style={styles.image} source={require('../../../images/collection-imag1.png')}/>
    <Image style={styles.image} source={require('../../../images/collection-imag2.png')}/>
</ScrollView>
Run Code Online (Sandbox Code Playgroud)

我尝试过各种宽度组合:null,height:null,flex:1,alignSelf等.上面的解决方案几乎可以工作,除了高度不是动态的.部分图像不可见.

Lwi*_*yat 32

"resizeMode"不是风格属性.应该移动到Image组件,Props如下面的代码.

const win = Dimensions.get('window');

const styles = StyleSheet.create({
    image: {
        flex: 1,
        alignSelf: 'stretch',
        width: win.width,
        height: win.height,
    }
});

...
    <Image 
       style={styles.image}
       resizeMode={'contain'}   /* <= changed  */
       source={require('../../../images/collection-imag2.png')} /> 
...
Run Code Online (Sandbox Code Playgroud)

图像的高度不会自动变为高,因为图像组件需要宽度和高度style props.所以你需要使用getSize()方法自己计算,你可以在这个答案中看到.

有很多有用的开源库,列表如下所示.

  • 根据https://facebook.github.io/react-native/docs/image.html,它是图像上的样式属性.将其更改为属性也不起作用. (4认同)
  • 这没有回答给定高度自动计算的问题 (4认同)
  • 这并没有从很多角度回答这个问题。除了上述注释中的内容外,[doc](https://facebook.github.io/react-native/docs/image#getsize)明确表示getSize()“不适用于静态图像资源”。 (2认同)

Vin*_*dam 28

所以经过一段时间的思考,我能够达到身高:自动反应原生图像.您需要知道图像的尺寸才能使这个黑客工作.只需在任何图像查看器中打开图像,您就可以在文件信息中获得图像的尺寸.作为参考,我使用的图像大小是541 x 362

首先从react-native导入维度

import { Dimensions } from 'react-native';
Run Code Online (Sandbox Code Playgroud)

那么你必须得到窗口的尺寸

const win = Dimensions.get('window');
Run Code Online (Sandbox Code Playgroud)

现在计算比率为

const ratio = win.width/541; //541 is actual image width
Run Code Online (Sandbox Code Playgroud)

现在添加样式为您的图像

imageStyle: {
    width: win.width,
    height: 362 * ratio, //362 is actual height of image
}
Run Code Online (Sandbox Code Playgroud)

  • 截至 2020 年 3 月,这仍然是最佳解决方案吗? (8认同)
  • 你是天才。我仍然无法弄清楚这一点。但它有效:) (2认同)
  • 如此聪明的解决方案 (2认同)
  • 是的!这是唯一一种在所有情况下都有效的方法。唯一需要考虑的是,如果这些是静态资源,您可以很容易地解析图像尺寸。只需执行:`import myImage from '../../assets/myimage.png'; const { 宽度, 高度 } = Image.resolveAssetSource(myImage)` (2认同)
  • 这怎么是正确的呢?图像的宽度是窗口宽度,而不是 100% (2认同)

Ara*_*han 22

如果您知道图像的宽高比(宽度/高度),我已经找到了width: "100%", height: "auto"的解决方案。

这是代码:

import { Image, StyleSheet, View } from 'react-native';

const image = () => (
    <View style={styles.imgContainer}>
        <Image style={styles.image} source={require('assets/images/image.png')} />
    </View>
);

const style = StyleSheet.create({
    imgContainer: {
        flexDirection: 'row'
    },
    image: {
        resizeMode: 'contain',
        flex: 1,
        aspectRatio: 1 // Your aspect ratio
    }
});
Run Code Online (Sandbox Code Playgroud)

这是我可以在不使用onLayout或Dimension计算的情况下使其工作的最简单的方法。如果需要,您甚至可以将其包装在一个简单的可重用组件中。如果有人正在寻找简单的实现,请试一试。


Tof*_*van 9

在样式中使用aspectRatio属性

纵横比控制节点未定义维度的大小。纵横比是一个非标准属性,仅在 react native 中可用,在 CSS 中不可用。

  • 在具有设置的宽度/高度纵横比的节点上控制未设置尺寸的大小
  • 如果未设置,则在具有设置的 flex 基础纵横比的节点上控制交叉轴中节点的大小
  • 在具有测量函数纵横比的节点上,测量函数就像测量 flex 基础一样工作
  • 在具有 flex 增长/收缩纵横比的节点上,如果未设置,则控制横轴中节点的大小
  • 纵横比考虑最小/最大尺寸

文档:https : //reactnative.dev/docs/layout-props#aspectratio

试试这样:

import {Image, Dimensions} from 'react-native';

var width = Dimensions.get('window').width; 

<Image
    source={{
        uri: '<IMAGE_URI>'
    }}
    style={{
        width: width * .2,  //its same to '20%' of device width
        aspectRatio: 1, // <-- this
        resizeMode: 'contain', //optional
    }}
/>
Run Code Online (Sandbox Code Playgroud)


Łuk*_*ski 8

我对上述所有解决方案都有问题。最后我使用 aspectRatio 来解决这个问题。当您知道图像的宽度和高度并且它们很大时,只需计算宽高比并将其添加到图像中,如下所示:

<PhotoImage
    source={{uri: `data:image/jpeg;base64,${image.base64}`}}
    style={{ aspectRatio: image.width / image.height }}
 />
Run Code Online (Sandbox Code Playgroud)

AspectRatio 是 React Native 的布局属性,用于保持图像的纵横比并适合父容器:https : //facebook.github.io/react-native/docs/layout-props#aspectratio

  • 这是唯一真正的答案。对此进行扩展。如果您从网络请求图像。您可以使用“react-native”中的“Image.getSize”静态方法获取大小 (2认同)

Dmi*_*nal 7

右键单击您的图像以获得分辨率。就我而言 1233\xe2\x80\x8ax\xe2\x80\x8a882

\n
const { width } = Dimensions.get('window');\n\nconst ratio = 882 / 1233;\n\n    const style = {\n      width,\n      height: width * ratio\n    }\n\n<Image source={image} style={style} resizeMode="contain" />\n
Run Code Online (Sandbox Code Playgroud)\n

这一切

\n


rcl*_*lai 6

你总是要设置一个宽度和高度Image.它不会为您自动调整大小.React Native文档说明了这一点.

你应该测量的总高度ScrollView使用onLayout和设置的高度Image基于它秒.如果你使用resizeMode的cover它会保持你的长宽比Image秒,但它显然裁剪他们,如果它比容器大.

  • 自动调整大小仅对远程图像不起作用.OP正在引用一个本地的静态图像文件,用React Native _"可以自动调整大小,因为它们的尺寸在安装时可以立即使用."_ (6认同)

小智 5

2020 年 4 月解决方案:

所以上面的答案很可爱,但它们都有(imo)一个很大的缺陷:它们正在计算图像的高度,基于用户设备的宽度。

要实现真正的响应式(即width: 100%, height: auto)实现,您真正想做的是根据父容器的宽度计算图像的高度。

幸运的是,由于onLayout View 方法,React Native 为我们提供了一种获取父容器宽度的方法。

所以我们需要做的就是创建一个带有 的视图width: "100%",然后使用它onLayout来获取该视图的宽度(即容器宽度),然后使用该容器宽度来适当地计算我们图像的高度。

 

直接给我看代码...

下面的解决方案可以进一步改进,通过使用RN 的 Image.getSize来获取 ResponsiveImage 组件本身内的图像尺寸。

JavaScript:

// ResponsiveImage.ts

import React, { useMemo, useState } from "react";
import { Image, StyleSheet, View } from "react-native";

const ResponsiveImage = props => {
  const [containerWidth, setContainerWidth] = useState(0);
  const _onViewLayoutChange = event => {
    const { width } = event.nativeEvent.layout;
    setContainerWidth(width);
  }

  const imageStyles = useMemo(() => {
    const ratio = containerWidth / props.srcWidth;
    return {
      width: containerWidth,
      height: props.srcHeight * ratio
    };
  }, [containerWidth]);

  return (
    <View style={styles.container} onLayout={_onViewLayoutChange}>
      <Image source={props.src} style={imageStyles} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { width: "100%" }
});

export default ResponsiveImage;


// Example usage...

import ResponsiveImage from "../components/ResponsiveImage";

...

<ResponsiveImage
  src={require("./images/your-image.jpg")}
  srcWidth={910} // replace with your image width
  srcHeight={628} // replace with your image height
/>
Run Code Online (Sandbox Code Playgroud)

 

打字稿:

// ResponsiveImage.ts

import React, { useMemo, useState } from "react";
import {
  Image,
  ImageSourcePropType,
  LayoutChangeEvent,
  StyleSheet,
  View
} from "react-native";

interface ResponsiveImageProps {
  src: ImageSourcePropType;
  srcWidth: number;
  srcHeight: number;
}

const ResponsiveImage: React.FC<ResponsiveImageProps> = props => {
  const [containerWidth, setContainerWidth] = useState<number>(0);
  const _onViewLayoutChange = (event: LayoutChangeEvent) => {
    const { width } = event.nativeEvent.layout;
    setContainerWidth(width);
  }

  const imageStyles = useMemo(() => {
    const ratio = containerWidth / props.srcWidth;
    return {
      width: containerWidth,
      height: props.srcHeight * ratio
    };
  }, [containerWidth]);

  return (
    <View style={styles.container} onLayout={_onViewLayoutChange}>
      <Image source={props.src} style={imageStyles} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { width: "100%" }
});

export default ResponsiveImage;


// Example usage...

import ResponsiveImage from "../components/ResponsiveImage";

...

<ResponsiveImage
  src={require("./images/your-image.jpg")}
  srcWidth={910} // replace with your image width
  srcHeight={628} // replace with your image height
/>
Run Code Online (Sandbox Code Playgroud)

  • 正如您所建议的,https://github.com/vivaxy/react-native-auto-height-image 对于这个问题做了很好的工作。感谢 (2认同)