React Native Image absolute positioning

localhost picture localhost · Feb 4, 2018 · Viewed 20.8k times · Source

I am trying to position two images at the bottom border, each side with the 50% width, so as to properly scale to any device size. But I can't seem to get any absolute positioning to behave in a reproducible way.

I've made an example Snack: https://snack.expo.io/rJd3OkVIM

The App component and the associated style is shown below:

import React, { Component } from 'react';
import { View, StyleSheet, Image } from 'react-native';


export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Image
                style={styles.img}
                resizeMode="contain"
                resizeMethod="resize"
                source={require('./leftbg.png')}
            />
        <Image
                style={styles.imgr}
                resizeMode="contain"
                resizeMethod="resize"
                source={require('./rightbg.png')}
            />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
  },
    img: {
      width: '50%',
      position: 'absolute',
      left: 0,
    },
    imgr: {
      width: '50%',
      position: 'absolute',
      right: 0,
    }
});

Each device sets the image vertical centering to a random part of the screen, every time the project is opened the centering seems to change.

Answer

Khoa picture Khoa · Feb 4, 2018

To achieve your requirement, let wrap 2 images to a View with flexDirection: 'row', then make the top level View with justityContent: 'flex-end'.

I made a simple code with hard code height for 200 px and put the background as goldenrod for easy recognization.

If you need to keep the ratio of image, follow this answer: Maintain aspect ratio of image with full width in React Native

import React, { Component } from 'react';
import { View, StyleSheet, Image } from 'react-native';


export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={{ flexDirection: 'row', height: 200, backgroundColor: 'goldenrod' }}>
          <Image
                style={styles.img}
                source={require('./leftbg.png')}
            />
          <Image
                  style={styles.imgr}
                  source={require('./rightbg.png')}
              />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
    justifyContent: 'flex-end',
  },
    img: {
      width: '50%',
      height: '100%',
      resizeMode: 'cover',
    },
    imgr: {
      width: '50%',
      height: '100%',
      resizeMode: 'cover',
    }
});