xaphod
xaphod

Reputation: 6804

React Native Image doesn't resize on device (iOS) orientation change?

I'm a React Native n00b, so perhaps I'm missing something brutally obvious.

      <Image
        source={signoutGradient}
        resizeMode="cover"
        style={{ height: 60, justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0,0,0,0)' }}
      >
        <Button
          title="SIGN OUT"
          color="#FFFFFF"
          onPress={this.onPressSignOut}
        />
      </Image>

... gives me this in portrait on my iOS device (good):

portrait

... but this in landscape mode (bad) when I rotate the device. How come? How to fix this? I am expecting that the size of the actual PNG image file doesn't matter, because it should get stretched to be larger if it needs to be. That doesn't seem to be happening.

landscape

Upvotes: 0

Views: 3573

Answers (2)

Austin Cline
Austin Cline

Reputation: 81

Yep adding flex: 1 to your image style should fix your issue. As long as you are setting only a default height and not a width. In my case I had set both width and height for my image and had the same issue when the device went landscape. Once I removed the width and added flex: 1 my issue was resolved

Upvotes: 0

SoZettaSho
SoZettaSho

Reputation: 1021

FYI the Dimensions module doesn't automatically update when the screen rotates. It is only an option if you can somehow detect the rotation and force a rerender.

One option is wrapping the components that need to be responsive with a View and then use the onLayout property. The function passed as onLayout will receive a {nativeEvent: { layout: {x, y, width, height}}} containing the View's updated position and dimensions any time they change; if you write these to the component's state you can automatically recalculate your new height and width and trigger a rerender when the screen rotates (e.g. set onLayout on your root View and update the image's width to be the width of the entire screen). You can ctrl+f for "onLayout" here.

The flex style prop also updates on rotation, so you could possibly set flex:1 for example on your root component and somehow use flexbox to keep everything styled responsively.

Upvotes: 1

Related Questions