如何将 resizeMode 设置为 "contain" 的 ImageBackground 放在顶部?

How to put ImageBackground with resizeMode set to "contain" at the top?

我目前正在使用以下代码在我的 React Native 应用程序上显示背景图片:

<ImageBackground 
   source={myImage} 
   style={{ width:'100%', height:'100%' }} 
   imageStyle={{resizeMode: 'contain'}}
>
....
</ImageBackground>

我不希望我的图像被拉伸,而 resizeMode: 'contain' 完美地完成了这项工作。这样图像就不会覆盖我的所有屏幕,而只会覆盖屏幕的一部分,这正是我想要实现的。

我的问题是图像与我上面显示的代码在中心垂直对齐,而我希望它保持在顶部。所以它应该保持比例并坚持在顶部。我尝试在 imageStyle 属性 中使用 position:'absolute'top:0 但它不起作用。

我看到 this question 这显然解释了我的同样问题,但它没有为我的问题提供解决方案。

你有什么建议吗?

嘿,我真的不明白你到底需要做什么,试试这个

body{
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  background: url(background.jpg) no-repeat;
  /* background-size: cover; */
}

试试这个:

import {Dimensions} from 'react-native'

    constructor(props) {
      super(props);
      this.state = { height: 0 };
    }

    componentDidMount(){
          Image.getSize(imgUrl, (srcWidth, srcHeight) => {
             const maxHeight = Dimensions.get('window').height; 
             const maxWidth = Dimensions.get('window').width;
             const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
             this.setState({ height: srcHeight * ratio})
          })
    } 

    <ImageBackground 
       source={myImage} 
       style={{ flex:1 }} 
       resizeMode= 'contain'
       imageStyle={height: this.state.height, width:Dimensions.get('window').width}
    >
    ....
    </ImageBackground>

ImageBackgroundImage 相同的道具所以 resizeMode 是道具而不是风格
看到这个:https://facebook.github.io/react-native/docs/imagebackground

我使用静态高度和 resizeMode 覆盖实现了类似的效果

<ImageBackground 
  style={{ flex: 1 }}
  imageStyle={{ height: 300 }}
  source={{ uri: entity.picture }}
  resizeMode="cover"
>
  ...
</ImageBackground>