我目前正在使用以下代码在我的 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>
ImageBackground
与 Image
具有相同的 props,因此 resizeMode
是一个 prop 而不是样式
请参阅:https://facebook.github.io/react-native/docs/imagebackground
关于css - 如何将resizeMode设置为 "contain"的ImageBackground放在顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55061767/