1

I have the following screen in my React Native app: enter image description here

The blue black and white background is an ImageBackground, and the green strip in the middle is a View. The code is:

<ImageBackground
  source={require('@images/login-background.jpg')}
  style={{
    flex: 1,
    width: '100%',
    resizeMode: 'cover',
    justifyContent: 'center',
  }}
>
  <View style={{
    width: '100%',
    backgroundColor: 'green',
    borderRadius: 15,
    padding: 15
  }}/>
  </ImageBackground>

I want there to be 15px of padding at the left and right edges of the green View. If the ImageBackground were a View I would've added 15px of padding to it, but when it's an ImageBackground that results in this:

enter image description here

Conversely, if I add margin: 15px to the green View, I get this:

enter image description here

How should I approach this, to make it look like this?

enter image description here

gkeenley
  • 6,088
  • 8
  • 54
  • 129

2 Answers2

2

You can achieve the above requirement using Dimensions in React-Native

import React from "react";
import { ImageBackground, View, Dimensions } from "react-native";

const screenWidth = Dimensions.get('window').width;

export default App = () => (
    <ImageBackground
        source={{ uri: "https://reactjs.org/logo-og.png" }}
        style={{
            flex: 1,
            width: '100%',
            resizeMode: 'cover',
            justifyContent: 'center',
            alignItems: 'center'
        }}>
        <View style={{
            width: screenWidth - 30,
            backgroundColor: 'green',
            borderRadius: 15,
            padding: 15
        }} />
    </ImageBackground>
);

Hope this helps you. Feel free for doubts.

SDushan
  • 4,341
  • 2
  • 16
  • 34
  • Ok yep, this works, thanks! Do you know if there's also a way to do it with padding or margin? – gkeenley Apr 24 '20 at 02:50
  • @gkeenley when you assign ```width: '100%'``` it automatically assign width according to the parent view. you can try adding ```marginHorizontal: 15, width: '90%'``` but that might not be an optimal solution. – SDushan Apr 24 '20 at 02:57
  • 1
    Yep, unfortunately that wouldn't work if the phone's going between portrait and landscape. I'll go ahead and use the Dimensions thing. Thanks! – gkeenley Apr 24 '20 at 02:59
2

Try this:

    <ImageBackground
      source={image}
      style={{
        flex: 1,
        width: '100%',
        resizeMode: 'cover',
        justifyContent: 'center',
      }}
    >
    <View style={{paddingHorizontal: 15}}>
      <View style={{
       width: '100%',
       backgroundColor: 'green',
       borderRadius: 15,
       padding: 15,
      }}/>
    </View>
    </ImageBackground>
Soufiane Odf
  • 1,054
  • 2
  • 9
  • 23
  • This is my fallback solution :) I'd rather do it without adding another `View`, but this does work, thank you. – gkeenley Apr 24 '20 at 02:54