Javascript 如何在本机反应中将图像宽度设置为 100% 并将高度设置为自动?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39631895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:45:21  来源:igfitidea点击:

How to set image width to be 100% and height to be auto in react native?

javascriptimagereactjsreact-native

提问by Prabhakar Bhat

I am trying to display list of images in a scrollview. Width should be 100%, while height should be automatic, keeping aspect ratio.

我正在尝试在滚动视图中显示图像列表。宽度应该是 100%,而高度应该是自动的,保持纵横比。

The searches I did pointed to various solutions which give fullscreen background style.

我所做的搜索指向了提供全屏背景样式的各种解决方案。

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>

I have tried various combinations of width: null, height: null, flex: 1, alignSelf etc. The above solution is almost working, except the height is not dynamic. Parts of the image are not visible.

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

回答by Vinit Kadam

So after thinking for a while I was able to achieve height: auto in react-native image. You need to know the dimensions of your image for this hack to work. Just open your image in any image viewer and you will get the dimensions of the your image in file information. For reference the size of image I used is 541 x 362

因此,经过一段时间的思考,我能够在 react-native 图像中实现 height: auto 。您需要知道图像的尺寸才能使此 hack 起作用。只需在任何图像查看器中打开您的图像,您就会在文件信息中获得图像的尺寸。作为参考,我使用的图像大小为 541 x 362

First import Dimensions from react-native

首先从 react-native 导入 Dimensions

import { Dimensions } from 'react-native';

then you have to get the dimensions of the window

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

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

Now calculate ratio as

现在计算比率为

const ratio = win.width/541; //541 is actual image width

now the add style to your image as

现在将样式添加到您的图像中

imageStyle: {
    width: win.width,
    height: 362 * ratio, //362 is actual height of image
}

回答by Lwin Kyaw Myat

"resizeMode"isn't style property. Should move to Image component's Propslike below code.

"resizeMode"不是样式属性。应该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')} /> 
...

Image's height won't become automatically because Imagecomponent is required both width and height in style props. So you can calculate by using getSize()method for remote images like this answerand you can also calculate image ratio for static images like this answer.

图像的高度不会自动变为,因为图像组件在style props. 因此,您可以使用getSize()方法计算像这个答案这样的远程图像,也可以计算像这个答案这样的静态图像的图像比例。

There are a lot of useful open source libraries -

有很多有用的开源库——

回答by rclai

You always have to set the width and height of an Image. It is not going to automatically size things for you. The React Native docs says so.

您始终必须设置Image. 它不会自动为您调整大小。React Native 文档是这么说的

You should measure the total height of the ScrollViewusing onLayoutand set the height of the Images based on it. If you use resizeModeof coverit will keep the aspect ratio of your Images but it will obviously crop them if it's bigger than the container.

您应该测量ScrollViewusing的总高度onLayoutImage根据它设置s的高度。如果你使用resizeModecover它会保持你的长宽比Image秒,但它显然裁剪他们,如果它比容器大。

回答by ?ukasz Blaszyński

I had problems with all above solutions. Finally i used aspectRatio to do the trick. When you know image width and height and they are large, just calculate aspectRatio and add it to image like:

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

<PhotoImage
    source={{uri: `data:image/jpeg;base64,${image.base64}`}}
    style={{ aspectRatio: image.width / image.height }}
 />

AspectRatio is a layout property of React Native, to keep aspect ratio of image and fit into parent container: https://facebook.github.io/react-native/docs/layout-props#aspectratio

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

回答by Tofa Maulana Irvan

use aspectRatioproperty in style

在样式中使用aspectRatio属性

Aspect ratio control the size of the undefined dimension of a node. Aspect ratio is a non-standard property only available in react native and not CSS.

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

  • On a node with a set width/height aspect ratio control the size of the unset dimension
  • On a node with a set flex basis aspect ratio controls the size of the node in the cross axis if unset
  • On a node with a measure function aspect ratio works as though the measure function measures the flex basis
  • On a node with flex grow/shrink aspect ratio controls the size of the node in the cross axis if unset
  • Aspect ratio takes min/max dimensions into account
  • 在具有设置的宽度/高度纵横比的节点上控制未设置尺寸的大小
  • 如果未设置,则在具有设置的 flex 基础纵横比的节点上控制交叉轴中节点的大小
  • 在具有测量函数纵横比的节点上,测量函数就像测量 flex 基础一样工作
  • 在具有 flex 增长/收缩纵横比的节点上,如果未设置,则控制横轴中节点的大小
  • 纵横比考虑最小/最大尺寸

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

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

try like this:

试试这样:

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
    }}
/>

回答by Jon James Designs

Solution April 2020:

2020 年 4 月解决方案:

So the above answers are cute but they all have (imo) a big flaw: they are calculating the height of the image, based on the width of the user's device.

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

To have a trulyresponsive (i.e. width: 100%, height: auto) implementation, what you reallywant to be doing, is calculating the height of the image, based on the width of the parent container.

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

Luckily for us, React Native provides us with a way to get the parent container width, thanks to the onLayout View method.

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

So all we need to do is create a View with width: "100%", then use onLayoutto get the width of that view (i.e. the container width), then use that container width to calculate the height of our image appropriately.

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

 

 

Just show me the code...

直接给我看代码...

The below solution could be improved upon further, by using RN's Image.getSize, to grab the image dimensions within the ResponsiveImage component itself.

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

JavaScript:

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
/>

 

 

TypeScript:

打字稿:

// 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
/>

回答by Arafat Zahan

I've found a solution for width: "100%", height: "auto"if you know the aspectRatio (width / height)of the image.

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

Here's the code:

这是代码:

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
    }
});

This is the most simplest way I could get it to work without using onLayoutor Dimensioncalculations. You can even wrap it in a simple reusable component if needed. Give it a shot if anyone is looking for a simple implementation.

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

回答by kallayya Hiremath

For image tag you can use this type of style, it worked for me:

对于图像标签,您可以使用这种类型的样式,它对我有用:

imageStyle: {
    width: Dimensions.get('window').width - 23,
    resizeMode: "contain",
    height: 211,
 },