【问题标题】:React Native: Why is image stretching vertically to fill container and how to prevent it?React Native:为什么图像垂直拉伸以填充容器以及如何防止它?
【发布时间】:2020-03-31 08:16:20
【问题描述】:

在我的 React Native 应用程序中,我有一个高度为 300 的红色框,我想垂直居中,我想在这个红色框的内部和顶部放置一个图像。到目前为止,这是我的代码:

import React, { Component } from 'react';
import { View, Image} from 'react-native';

export default class Login extends Component {
  render() {
    return (
      <View style={{
          flex: 1,
          justifyContent: "center",
          alignItems: "center"
        }}>
          <View
            style={{
              borderWidth: 3,
              borderColor: 'red',
              width: "100%",
              height: 300
            }}
          >
            <Image
              source={require('../../images/swoord-top.png')}
              style={{
                width: "100%",
                height: "100%",
                resizeMode: "contain",
                borderWidth: 3
              }}
              >
            </Image>
          </View>
      </View>
    );
  }
}

这是这样的:

红框是我提到的外框,黑框正好是Image的边框。问题是这个黑框(即Image)会扩展以垂直填充红色框,并且图像在这个黑框内垂直居中,所以它在红框内垂直居中,而不是flex-start我想要的位置。我尝试将justifyContent: flex-startflexShrink: 1 添加到Image 中,但都没有产生任何影响。

有人知道我该如何处理吗?

注意:

如果我删除 Image 上的 height: 100%,我会得到:

更新:

澄清一下,这就是我想要的样子。我已经删除了这里的黑色边框。我通过添加top: -95 将它移到我想要的位置,但这通常不起作用,因为不同设备的值会有所不同:

【问题讨论】:

  • 你能给我们看一张图片,我们可以看到你想要实现的目标吗?

标签: reactjs react-native react-native-image


【解决方案1】:

尝试这样做

 <Image
              source={require('../../images/swoord-top.png')}
              style={{
                width: "100%",
                borderWidth: 3
              }}
              resizeMode={"contain"}
              />

【讨论】:

  • 嗨,尼拉姆,很遗憾,没有区别。
  • 移除图片的高度,然后尝试
  • 在原帖中查看我的“注意:”
【解决方案2】:

图像(视图)和该图像的内容之间存在差异。在您的屏幕截图中,图像视图具有黑色边框,其内容位于其中。因为它们具有不同的纵横比,所以内容上要么有空白,要么有截断。您无法调整内容的位置,因为它不是基于弹性布局的。图像视图只是一个呈现图像内容的窗口。没有属性可以告诉 Image 在哪里对齐该内容

您的问题来自屏幕宽度不同的事实,并且容器的纵横比也不同(可变宽度但恒定 300 高度)。你需要做的是

  1. 测量容器宽度
  2. 根据图片资源的宽度和高度确定图片的合适纵横比
  3. 根据收到的纵横比将图像宽度设置为 100% 并设置其高度

这里,我的图片尺寸是 1005 * 219:

const Test = () => {
  const [width, setWidth] = useState(0);
  return (
    <View>
      <View
        onLayout={e => setWidth(e.nativeEvent.layout.width)}
        style={{ width: '100%', height: 300, borderWidth: 1 }}>
        <Image
          style={{
            width: '100%',
            height: (width / 1005) * 219,
            borderWidth: 1,
            borderColor: 'red',
          }}
          source={require('...')}
        />
      </View>
    </View>
  );
};

【讨论】:

    猜你喜欢
    • 2016-01-03
    • 2023-03-31
    • 1970-01-01
    • 2012-09-18
    • 2019-03-10
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 2015-03-13
    相关资源
    最近更新 更多