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

时间:2016-09-22 06:37:18

标签: 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>

我尝试过各种宽度组合:null,height:null,flex:1,alignSelf等。上述解决方案几乎正常,但高度不是动态的。部分图像不可见。

12 个答案:

答案 0 :(得分:26)

<tx:annotation-driven transaction-manager="txManager" order="200" /> <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"> </bean> @Service public class OrderService extend BaseService<Order, Long> { @Transactional public Long save(Order modelEntity) { try{ super.save(modelEntity); } catch(Exception exp){ .... } } } ------------------------------ @Controller @RequestMapping("/test/core/Order") public class OrderController extends BaseController{ @Autowired(required = true) private IOrderService iOrderService; @RequestMapping(value = "/save", method = RequestMethod.POST) @ResponseBody public Long save(@RequestBody Order modelEntity) { return iOrderService.save(modelEntity); } } @Controller public class BaseController { @ExceptionHandler(Exception.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public ResponseEntity<String> handleUncaughtException(Exception ex, WebRequest request, HttpServletResponse response) throws IOException { String logMessage = ex.toString() + " " + ex.getMessage(); if (ex.getCause()!= null) { logMessage += ex.getCause().toString() + " " + ex.getCause().getMessage(); } return new ResponseEntity<String>(" ", responseHeaders, HttpStatus.INTERNAL_SERVER_ERROR); } 不是样式属性。应该转移到图像组件的"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')} /> ... 中的图像组件同时需要宽度和高度。因此,您可以使用getSize()方法计算this answer等远程图像,还可以计算this answer等静态图像的图像比率。

有很多有用的开源库 -

答案 1 :(得分:20)

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

首先从react-native

导入尺寸
import { Dimensions } from 'react-native';

然后你必须得到窗口的尺寸

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

现在将比率计算为

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

现在将图像添加样式为

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

答案 2 :(得分:10)

如果您知道图像的 aspectRatio(宽度/高度),我就找到了解决方案:宽度:“ 100%”,高度:“自动”

这是代码:

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

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

答案 3 :(得分:6)

您必须始终设置Image的宽度和高度。它不会自动为您调整大小。 React Native文档says so

您应该使用ScrollView来衡量onLayout的总高度,并根据它设置Image的高度。如果您使用resizeMode的{​​{1}},它将保留cover的宽高比,但如果它大于容器,则显然会裁剪它们。

答案 4 :(得分:4)

使用样式中的 aspectRatio 属性

纵横比控制节点的未定义尺寸的大小。长宽比是一种非标准属性,仅可用于react native而非CSS。

  • 在设置了宽/高长宽比的节点上,控制 未设置尺寸
  • 在具有设置的flex基础高宽比的节点上,控制 交叉轴上的节点是否未设置
  • 在具有度量函数高宽比的节点上, 测量功能测量弹性基础
  • 在具有flex增长/收缩纵横比的节点上,控制尺寸 交叉轴上的节点是否未设置
  • 长宽比考虑了最小/最大尺寸

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

尝试这样:

{{1}}

答案 5 :(得分:4)

2020年4月的解决方案:

因此,以上答案很可爱,但它们都有(imo)一个大缺陷:根据用户设备的宽度计算图像的高度

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

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

因此,我们要做的就是使用width: "100%"创建一个View,然后使用onLayout获取该视图的宽度(即容器宽度),然后使用该容器宽度来计算高度适当地显示我们的形象。

只给我看看代码...

通过使用RN's 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
/>

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

答案 6 :(得分:2)

让我分享我最终得到的结果,它允许通过获取图像尺寸来正确设置宽度或高度。此外,该代码允许在传输我们需要的大图像数据时获取加载图像:

  1. 使用静态方法 Image.prefetch 下载图像并可供缓存。

  2. 使用静态方法Image.getSize收集高度和宽度并用它来计算纵横比,然后计算最终的高度(或宽度)

  3. 以您喜欢的宽度的默认样式显示图像(将在保持纵横比的情况下计算高度)

     function ImageX(props: {source: string, id: string})
     {
       const [imageHeight, setImageHeight] = React.useState(1);
       Image.prefetch(props.source)
       .then(() => {
           Image.getSize(props.source, (width, height) => {
             let aspectRatio =  height/width;
             setImageHeight(aspectRatio*Dimensions.get('window').width);
           });
       })
       .catch(error => console.log(error))
       if (imageHeight <=1) //Image not in cache (disk) yet
         {
           return (
             <Image key={props.id} style={styleimg.image} source={{uri: 'http://www.dsdsd/loaderpreview.gif'}}/>
           );
       }
       else
       {
         return (
           <Image key={props.id} style={styleimg.image} height={imageHeight} source={{uri: props.source}}/>
         );
       }
     }
    

    const styleimg = StyleSheet.create({ 图像: { 宽度:Dimensions.get('window').width, 调整大小模式:'包含' //... // 您可以设置高度默认值 } });

答案 7 :(得分:1)

对于图片标签,您可以使用这种样式,它对我有用:

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

答案 8 :(得分:0)

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

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

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

答案 9 :(得分:0)

这可能有助于自动调整图像宽度为100%的图像高度

图片:{ 宽度:“ 100%”, resizeMode:“中心”“包含”, 高度:未定义, AspectRatio:1 }

答案 10 :(得分:0)

右键单击图像以获取分辨率。以我为例1233 x 882

const { width } = Dimensions.get('window');

const ratio = 882 / 1233;

    const style = {
      width,
      height: width * ratio
    }

<Image source={image} style={style} resizeMode="contain" />

全部

答案 11 :(得分:-2)

---
No client certificate CA names sent
Peer signing digest: SHA256
Peer signature type: RSA
Server Temp Key: ECDH, P-256, 256 bits
---
SSL handshake has read 3851 bytes and written 438 bytes
Verification error: unable to get local issuer certificate
---
New, TLSv1.2, Cipher is ECDHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : ECDHE-RSA-AES256-GCM-SHA384
    Session-ID: 441C92CFBEA27773315E4A9476C3A5173F0A2AB0AADDE708568DD8752EAA8A5A
    Session-ID-ctx:
    Master-Key: DF6DB0BC64F84ADD5974694845136249AEBEFB2559009AAD2A5C27A6FC981915AB50A765914CAA8AFCAC904B9998FF54
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1614064531
    Timeout   : 7200 (sec)
    Verify return code: 20 (unable to get local issuer certificate)
    Extended master secret: no
---
depth=2 C = US, O = "Blue Coat Systems, Inc.", CN = Cloud Services CA - G2
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=1 C = US, O = Cloud Services, OU = Operations, CN = SSL-SG1-GINCH7
verify return:1
depth=0 C = US, ST = California, L = San Francisco, O = "GitHub, Inc.", CN = github.com
verify return:1

使用来自 https://reactnativeelements.com/docs/image 的 Image 组件