React Native - 使用resizeMode"包含"垂直对齐图像

Kyl*_*son 34 react-native

当图像具有调整大小模式"包含"时,它似乎在中心对齐/对齐实际图像,但是图像内容在弯曲开始时对齐/对齐.

<Image resizeMode="contain" ...>
<Text>Title</Text>
</Image>
Run Code Online (Sandbox Code Playgroud)

以下我看到文字出现在图像上方.

有没有办法将包含的图像垂直对齐到顶部?

Som*_*gOn 9

我能够使用以下代码模拟CSS backgroundPosition:

<View style={{ overflow: 'hidden' }}>
  <Image src={{ uri: imageURI }} style={{ height: /*adjust_as_needed*/, resizeMode: 'cover' }} />
</View>
Run Code Online (Sandbox Code Playgroud)

由于溢出:"隐藏"在视图上可以调整图像的高度而不会看到图像的额外高度.你需要用户'覆盖'而不是'包含'用于调整大小模式,否则如果你将图像的高度设置得太大,你最终会得到一个不像View容器那样宽的居中图像.

在下面的顶部示例中,图像高度(蓝色虚线)大于底部示例,因此图像的中心线在视图中位于较低位置.通过在第二示例中减小图像的高度(蓝色虚线),图像的中心线在视图中向上移动.

希望这是有道理的,我希望它适用于您的用例; 它为我做了:D

在此输入图像描述


Cor*_* S. 5

您需要在图像上使用样式来设置所需的垂直对齐方式。

var SampleApp = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Image source={{uri: "http://placekitten.com/300/505"}} style={styles.image}>
          <Text style={styles.instructions}>
            Hello !
            </Text>
        </Image>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
    backgroundColor: '#F5FCFF',
  },
  image: {
    height: 500,
    justifyContent: "space-around",    //  <-- you can use "center", "flex-start",
    resizeMode: "contain",             //      "flex-end" or "space-between" here
  },
  instructions: {
    textAlign: 'center',
    color: 'white',
    backgroundColor: "transparent",
    fontSize: 25,
  },
});
Run Code Online (Sandbox Code Playgroud)

有关正在运行的示例,请参见https://rnplay.org/apps/9D5H1Q


Zac*_*han 5

使用 resizeMethod="resize"

我找到了一个不需要任何额外标签或技巧的解决方案。只有一个道具。

知识

我遇到了同样的问题,因为我在遥控器上的图像是常规尺寸的 @3 倍。一旦将{ height: 100, width: 300, resizeMode: 'contain' }样式值加载到手机上,它就会自动居中。

例子

为了修复它,我刚刚添加resizeMethod了如下道具:

<Image
  style={{ height: 100, width: 300, resizeMode: 'contain' }}
  source={{ uri: 'https://www.fillmurray.com/900/300' }}
  resizeMode="contain"
  resizeMethod="resize"
/>
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!

  • 不适用于百分比高度/宽度,仅适用于硬编码值。 (4认同)