Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native backgroundColor overlay over image

I am using an image as the background for one of my pages. I'd like to add a backgroundColor with an opacity over the image. I'm not sure how I can achieve this with React Native.

render() {
  return (
    <Image source={require('./assets/climbing_mountain.jpeg')} style={styles.container}>
      <Text>Hello</Text>
    </Image>
  )
}

const styles = StyleSheet.create({
  container: {
  flex: 1,
  width: null,
  height: null,
}

Here is how I'd achieve this on a web page: How to make in CSS an overlay over an image?

like image 463
Molly Harper Avatar asked Jan 13 '17 02:01

Molly Harper


2 Answers

A cool thing you can do is drop an absolutely positioned view over it.

<View>
  <Image source={require('./assets/climbing_mountain.jpeg')} style=  {StyleSheet.absoluteFillObject}} resizeMode='cover'>
    <Text>Hello</Text>
  </Image>
  <View style={styles.overlay} />
</View>

...
const styles = StyleSheet.create({
   overlay: {
     ...StyleSheet.absoluteFillObject,
     backgroundColor: 'rgba(0,0,0,0.5)'
   }
 })

absoluteFillObject is the same as

{
 position: 'absolute',
 top: 0,
 left: 0,
 right: 0,
 bottom: 0
}

If you want to be able to tap through your overlay, just set the pointerEvents prop on the view to none

docs: https://facebook.github.io/react-native/docs/stylesheet.html#absolutefillobject

like image 160
Kevin Velasco Avatar answered Sep 20 '22 17:09

Kevin Velasco


I was able to get this working thanks to @Kevin Velasco.

render() {
  return (
    <View style={styles.container}>
      <Image source={require('./assets/climbing_mountain.jpeg')} style={styles.imageContainer}>
      </Image>
      <View style={styles.overlay} />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: null,
    height: null,
  },
  imageContainer: {
    flex: 1,
    width: null,
    height: null,
  },
  overlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(69,85,117,0.7)',
  }
})
like image 30
Molly Harper Avatar answered Sep 18 '22 17:09

Molly Harper