如何在 react-native 中动态缩放图像?

How to dynamically scale an image in react-native?

我希望图像显示在整个屏幕的宽度上,并进行缩放以保持其比例。

我目前有这个

<ScrollView style={styles.background}>
<Text>Some Header Text</Text>
 <Image
    style={{width: null}}
    resizeMode="contain"
    source={require("./assets/images/map.png")}
   />
</ScrollView>

哪一半有效。图像宽度正确缩放。但它保留了它的高度,所以图片上方和下方有一个大边框。(即布局仍在使用未缩放的图片高度)

如果我添加 height: null 或用 height 替换宽度,则不会显示任何图像。

我该如何做这件(我期望的)微不足道的事情? (在 ios 和 android 上的行为相同。)

所以我不得不自己计算。

这会根据我的需要缩放图像,当 phone 旋转时图像会重新缩放。

我不确定 componentWillMount 是否是选择计算 width/height 比率的正确事件。我很乐意收到任何其他代码审查评论!

import React, {Component} from "react";
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  Button,
  Dimensions
} from "react-native";
import resolveAssetSource from "resolveAssetSource";
import {Actions} from "react-native-router-flux";

export default class Main extends Component {
  measureView(event) {
    this.setState({
       width: event.nativeEvent.layout.width,
       height: event.nativeEvent.layout.width
    });
  }
  componentWillMount() {        
    let source = resolveAssetSource(require("./assets/images/map.png"));
    this.setState({ratio: source.height / source.width});
  }
  render() {
    return (
      <ScrollView           
        onLayout={event => this.measureView(event)}
      >
        <Text style={styles.header}>
          Some Header Text
        </Text>

        <Image
          style={{
            width: this.state.width,
            height: this.state.width * this.state.ratio
          }}
          resizeMode="contain"
          source={require("./assets/images/map.png")}
        />  
      </ScrollView>
    );
  }
}