如何使用React Native强制图像为全宽并保持纵横比?

rseugnpd  于 2023-01-18  发布在  React
关注(0)|答案(8)|浏览(149)

我有一个图像,我从一个网址拉下来。我不知道这个图像的尺寸提前。
如何设置图像的样式/布局,使其为父视图的全宽,并计算高度以保持纵横比?
我试过在0.34.0-rc.0中使用onLoad,在event.nativeEvent.source中高度/宽度都是0。
图像是在一个<ScrollView/>。我不是在一个全屏图像。

pbpqsu0x

pbpqsu0x1#

我的使用非常相似,我需要显示一个图像与全屏宽度,但保持其纵横比
基于@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>
    )
  }
}
plupiseo

plupiseo2#

我对react-native不熟悉,但我遇到了这个使用简单风格的解决方案:

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

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

对我很有效。

yhxst69z

yhxst69z3#

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

6mw9ycah

6mw9ycah4#

对我很有效。

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

当您从layout事件中获得父视图宽度时,您可以将宽度分配给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;
jm81lzqq

jm81lzqq5#

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

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

u91tlkcl6#

试试这个:传递图像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), 
          })}
        }
      />
    );
  }
}
dnph8jn4

dnph8jn47#

在我的情况下,它为我改变纵横比和图像的弯曲像这样工作

flex:1,aspectRatio:1.2, height:null
fzwojiic

fzwojiic8#

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

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

相关问题