【问题标题】:How to dynamically scale an image in react-native?如何在 react-native 中动态缩放图像?
【发布时间】:2017-06-28 11:33:33
【问题描述】:

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

我现在有这个

<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 上的行为相同。)

【问题讨论】:

  • 你能显示截图你的输出应该是什么样子吗?你需要背景图片还是可以滚动的?
  • 它应该是可滚动的。只是标题下方的图片,适合纵向或横向屏幕尺寸。
  • 你可以试试style={height: 100, width: Dimensions.get('window').width} resizeMode="cover"。
  • 好吧,“工作”,但将高度固定为 100 像素...我希望这是完整图像...我想我可以做数学,但默认情况下不会发生这种情况?
  • 你在滚动视图中,否则 flex: 1 可以解决问题..

标签: image react-native expo


【解决方案1】:

所以我不得不自己计算。

这会根据需要缩放图像,并且在旋转手机时会重新缩放图像。

我不确定componentWillMount 是否是选择计算宽度/高度比的正确事件。我很乐意接受任何其他代码审查 cmets!

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2012-08-05
    • 2020-05-01
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多