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

标签 css react-native background-image

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

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

我不希望图像拉伸(stretch),而 resizeMode: 'contain' 完美地完成了这项工作。这样图像就不会覆盖我的整个屏幕,而只会覆盖其中的一部分,这正是我想要实现的目标。

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

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

你有什么建议吗?

最佳答案

试试这个:

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 具有相同的 props,因此 resizeMode 是一个 prop 而不是样式
请参阅:https://facebook.github.io/react-native/docs/imagebackground

关于css - 如何将resizeMode设置为 "contain"的ImageBackground放在顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55061767/

相关文章:

javascript - 如何从具有多个对象的平面列表中设置和获取不同的状态和输入

react-native - 如何在 native react 中将状态传递给静态导航?

react-native - 将左侧的后退按钮和中间的文本对齐

jquery - 使用 jQuery 从背景图像获取尺寸

CSS:背景图像拉伸(stretch)和挤压到 div 的 100% 区域,没有溢出,没有重复

CSS3 关键帧动画不起作用

css - 使用::after 时的边界半径问题

html - css:使最大宽度的中心元素在没有表格的情况下可用

css - 为什么背景图像不是 :url ('bg.jpg' ); working?

html - Firefox 和 Chrome 之间的 CSS 差异