0

在我的 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-startandflexShrink: 1并且Image两者都没有改变。

有谁知道我该如何解决这个问题?

笔记:

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

在此处输入图像描述

更新:

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

在此处输入图像描述

4

2 回答 2

0

图像(视图)和该图像的内容之间存在差异。在您的屏幕截图中,图像视图具有黑色边框,其内容位于其中。因为它们具有不同的纵横比,所以内容上要么有空白,要么有截断。您无法调整内容的位置,因为它不是基于弹性布局的。图像视图只是一个呈现图像内容的窗口。没有属性可以告诉 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>
  );
};
于 2020-03-31T08:42:23.090 回答
0

尝试这样做

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

于 2020-03-31T08:29:10.943 回答