【问题标题】:React-Native Image Height (Full Width)React-Native 图像高度(全宽)
【发布时间】:2017-01-22 15:49:44
【问题描述】:

我有一张从网址拉下来的图片。我提前不知道这张图片的尺寸。

如何设置<Image/> 的样式/布局,使其成为父视图的全宽并计算高度以保持纵横比?

我尝试在 0.34.0-rc.0 中使用 onLoad 并且在 event.nativeEvent.source 中的高度/宽度均为 0。

图片位于<ScrollView/>。我不是全屏图像。

【问题讨论】:

标签: image react-native full-width


【解决方案1】:

React Native 有一个内置函数可以返回图像的宽度和高度:Image.getSize()Check out the documentation here

【讨论】:

    【解决方案2】:

    我的使用非常相似,因为我需要显示具有全屏宽度保持其纵横比的图像。

    基于@JasonGaare 对使用Image.getSize() 的回答,我想出了以下实现:

    class PostItem extends React.Component {
    
      state = {
        imgWidth: 0,
        imgHeight: 0,
      }
    
      componentDidMount() {
    
        Image.getSize(this.props.imageUrl, (width, height) => {
          // calculate image width and height 
          const screenWidth = Dimensions.get('window').width
          const scaleFactor = width / screenWidth
          const imageHeight = height / scaleFactor
          this.setState({imgWidth: screenWidth, imgHeight: imageHeight})
        })
      }
    
      render() {
    
        const {imgWidth, imgHeight} = this.state
    
        return (
          <View>
            <Image
              style={{width: imgWidth, height: imgHeight}}
              source={{uri: this.props.imageUrl}}
            />
            <Text style={styles.title}>
              {this.props.description}
            </Text>
          </View>
        )
      }
    }
    

    【讨论】:

    • 感谢代码!我一直在使用组件 react-native-fit-image 但加载图像时遇到很多问题,有时无法渲染我对您的代码所做的独特修改是图像的样式是&lt;Image style={{width: imgWidth, height: imgHeight}} source={{uri: this.props.imageUrl}} /&gt;
    • 我在哪里提到图片的实际网址?
    • 'Dimensions' is not defined.
    • @PhilippLudwig import { Dimensions } from 'react-native';
    【解决方案3】:

    如果你还不能解决,React Native v.0.42.0 有 resizeMode

    <Image style={styles.intro_img} source={require('img.png')} 
    

    【讨论】:

      【解决方案4】:

      它对我有用。

      import React from 'react'
      import { View, Text, Image } from 'react-native'
      
      class Test extends React.Component {
        render() {
          return (
            <View>
              <Image
                source={{ uri: "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQL6goeE1IdiDqIUXUzhzeijVV90TDQpigOkiJGhzaJRbdecSEf" }}
                style={{ height: 200, left: 0, right: 0 }}
                resizeMode="contain"
              />
              <Text style={{ textAlign: "center" }}>Papaya</Text>
            </View>
          );
        }
      }
      
      export default Test;
      

      在布局事件后获取父视图宽度的另一种方法。

      <View 
        style={{ flex: 1}} 
        layout={(event) => { this.setState({ width: event.nativeEvent.layout.width }); }}
      />
      

      当您从布局事件中获取宽度父视图时,您可以将宽度分配给图像标签。

      import React from 'react';
      import { View, Image } from 'react-native';
      
      class Card extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            height: 300,
            width: 0
          };
        }
        render() {
          return (
            <View style={{
              flex: 1,
              flexDirection: 'row'
            }}>
              <View style={{ width: 50, backgroundColor: '#f00' }} />
              <View
                style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fafafa' }}
                onLayout={(event) => { this.setState({ width: event.nativeEvent.layout.width }); }}
              >
                {
                  this.state.width === 0 ? null : (
                    <Image
                      source={{ uri: "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQL6goeE1IdiDqIUXUzhzeijVV90TDQpigOkiJGhzaJRbdecSEf" }}
                      style={{ width: this.state.width, height: this.state.height }}
                      resizeMode="contain"
                    />
                  )
                }
              </View>
            </View>
          );
        }
      }
      export default Card;
      

      【讨论】:

        【解决方案5】:

        我是 react-native 的新手,但我使用简单的样式遇到了这个解决方案:

        imageStyle: {
          height: 300,
          flex: 1,
          width: null}
        

        来自我的 1º 应用的全宽图像:

        它对我有用。

        【讨论】:

        • 这似乎确实有效。 PS:我不得不删除我的 resizeMode="contain"。
        • 这如何回答原始问题?你必须知道前方图像的高度......
        【解决方案6】:

        如果你有一个静态图像,你可以像这样使用

        import React, { Component } from "react";
        import { View, Animated, Image, Dimensions } from "react-native";
        import splashScreen from "../../../assets/imgs/splash-screen.png";
        
        export default class MasterPage extends Component {
          constructor(props) {
            super(props);
            this.state = {
              fadeAnim: new Animated.Value(0),
              imgWidth: 0,
              imgHeight: 0
            };
          }
          checkLogIn = async () => {
            const width = 533; // set your local image with
            const height = 527; // set your local image height 
            // calculate image width and height
            const screenWidth = Dimensions.get("window").width;
            const scaleFactor = width / screenWidth;
            const imageHeight = height / scaleFactor;
            this.setState({ imgWidth: screenWidth, imgHeight: imageHeight });
          };
        
          async componentDidMount() {
            Animated.timing(
              // Animate over time
              this.state.fadeAnim, // The animated value to drive
              {
                toValue: 1, // Animate to opacity: 1 (opaque)
                duration: 800, // Make it take a while
                useNativeDriver: true
              }
            ).start(this.checkLogIn);
          }
        
          render() {
            const { imgWidth, imgHeight, fadeAnim } = this.state;
            return (
              <Animated.View
                style={{
                  opacity: fadeAnim,
                  backgroundColor: "#ebebeb",
                  flex: 1,
                  justifyContent: "center",
                  alignItems: "center"
                }}
              >
                <View>
                  <Image
                    source={splashScreen}
                    style={{ width: imgWidth, height: imgHeight }}
                  />
                </View>
              </Animated.View>
            );
          }
        }
        

        【讨论】:

          【解决方案7】:

          试试这个: 传递图像uri 和 parentWidth(可以是const { width } = Dimensions.get("window");),瞧……您可以根据宽度和纵横比自动计算高度

          import React, {Component} from 'react';
          import FastImage from 'react-native-fast-image';
          
          interface Props {
            uri: string;
            parentWidth: number;
          }
          
          interface State {
            calcImgHeight: number;
            width: number
            aspectRatio: number
          }
          
          export default class CustomFastImage extends Component<Props, State> {
            constructor(props: Props) {
              super(props);
              this.state = {
                calcImgHeight: 0,
                width: props.parentWidth,
                aspectRatio: 1
              };
            }
            componentDidUpdate(prevProps: Props){
              const { aspectRatio, width }= this.state
              const { parentWidth} = this.props
             
              if( prevProps.parentWidth !== this.props.parentWidth){
                  this.setState({
                      calcImgHeight: aspectRatio * parentWidth,
                      width: parentWidth
                    })
              }
            }
            render() {
              const {calcImgHeight, width} = this.state;
              const {uri} = this.props;
              return (
                <FastImage
                  style={{width: width, height: calcImgHeight}}
                  source={{
                    uri,
                  }}
                  resizeMode={FastImage.resizeMode.contain}
                  onLoad={(evt) =>
                    {
                        this.setState({
                      calcImgHeight: (evt.nativeEvent.height / evt.nativeEvent.width) * width, // By this, you keep the image ratio
                      aspectRatio:  (evt.nativeEvent.height / evt.nativeEvent.width), 
                    })}
                  }
                />
              );
            }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-01-12
            • 2016-08-17
            • 2016-01-30
            • 1970-01-01
            相关资源
            最近更新 更多