Reputation: 913
I'm currently displaying a background image on my React Native app using the following code:
<ImageBackground
source={myImage}
style={{ width:'100%', height:'100%' }}
imageStyle={{resizeMode: 'contain'}}
>
....
</ImageBackground>
I don't want my image to stretch and the resizeMode: 'contain'
does perfectly this job. In this way the image won't cover all my screen but only a portion of it and this is exactly what I want to achieve.
My issue is that the image is vertical aligned at the center with the code I shown above while I would like it to stick at the top. So it should keep proportions and stick at the top. I tried to use position:'absolute'
and top:0
in the imageStyle property but it doesn't work.
I saw this question which apparently explain my same problem but it doesn't provide a solution to my issue.
Do you have any suggestion?
Upvotes: 2
Views: 4130
Reputation: 1
Just use an Image component instead. And set the style to width: '100%';
Upvotes: -1
Reputation: 21
I achieved a similar effect using static height and resizeMode cover
<ImageBackground
style={{ flex: 1 }}
imageStyle={{ height: 300 }}
source={{ uri: entity.picture }}
resizeMode="cover"
>
...
</ImageBackground>
Upvotes: 1
Reputation: 1313
try this:
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
as the same props as Image
so resizeMode
is a prop not a style
See this: https://facebook.github.io/react-native/docs/imagebackground
Upvotes: 2