首页 文章

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

提问于
浏览
30

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

<Image resizeMode="contain" ...>
<Text>Title</Text>
</Image>

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

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

4 回答

  • 4

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

    <View style={{ overflow: 'hidden' }}>
      <Image src={{ uri: imageURI }} style={{ height: /*adjust_as_needed*/, resizeMode: 'cover' }} />
    </View>
    

    由于视图上的 overflow: 'hidden' ,可以调整图像的高度,而无需查看图像的额外高度 . 如果将图像的高度设置得太大,则'll need to user '封面' rather than '包含' for the resize mode as well otherwise you' ll最终会显示一个不如View容器宽的居中图像 .

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

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

    enter image description here

  • 6

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

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

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

  • 0

    我需要做同样的事情 . 我发现实现这一目标的最佳方法是明确给出图像的高度或宽度 . 然后,通过将图像包装在其他组件中,您可以使用justifyContent来完全控制图像的位置 .

    确实,您可能并不总是拥有图像的宽度或高度 . 但是,经常(特别是使用resizeMode:'contains')你想要设置相对于某些东西的高度或宽度 . 我希望高度等于视口的宽度 . 这是我使用的解决方案:

    <View style={{ flex: 1, justifyContent: 'flex-start' }}>
        <Image
          source={{ uri: imagePath }}
          resizeMode="contain"
          style={{ height: vw(100) }}
        />
     </View>
    

    vw是一个来自this答案的辅助函数 .

  • -1

    你需要在不设置的情况下修复另一个值 . 在大多数情况下,让宽度固定 . 小心使用父flex选项 . 它可能会改变你的设计 .

相关问题