29

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

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

我试过onLoad在 0.34.0-rc.0 中使用,高度/宽度都是 0 in event.nativeEvent.source.

图像位于<ScrollView/>. 我不追求全屏图像。

4

7 回答 7

29

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

基于@JasonGaare 对 use 的回答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>
    )
  }
}
于 2017-02-16T08:43:58.550 回答
24

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

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

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

它对我有用。

于 2018-02-24T02:30:00.957 回答
7

React Native 有一个内置函数,可以返回图像的宽度和高度:Image.getSize(). 在此处查看文档

于 2016-09-14T18:53:18.883 回答
7

它对我有用。

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

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

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;
于 2017-04-08T13:51:57.213 回答
2

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

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>
    );
  }
}
于 2019-10-06T18:04:04.680 回答
0

试试这个:传递图像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), 
          })}
        }
      />
    );
  }
}
于 2021-03-17T17:23:51.293 回答
-5

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

<Image style={styles.intro_img} source={require('img.png')} 
于 2017-03-10T04:24:12.887 回答