BenBtg
BenBtg

Reputation: 836

How do I center one image over another in React Native

I'm trying to make a clock component with a face image and a needle centered on the clock in React Native. does not allow embedding other Images. I found a few posts for centering text over images but cannot find any way do center Image over images.

Edit: I'm trying to find a way that avoids giving absolute position so the component can be dynamically sized.

Upvotes: 2

Views: 7021

Answers (2)

Ayush Nawani
Ayush Nawani

Reputation: 664

If i understood correctly, you want to show one image over other image. With one as a Parent image and other as a child image without using absolute postion. For this you can use ImageBackground Component provided by react-native and by setting its height and width with percentage value.

Below is the example :

Parent Image : Clock.png is an ImageBackground Component

Child Image : Needle.png is an Image Component

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

export default class ImageView extends Component {
  render() {
    return (
      <View
        style={{
          flex: 1
        }}
      >
        <View
          style={{
            flex: 0.25,
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: 'red'
          }}
        >
          <Text style={{ color: 'white', fontSize: 26 }}>I am Header</Text>
        </View>
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
            // backgroundColor: 'blue',
            borderWidth: 1,
            borderColor: 'red'
          }}
        >
          <ImageBackground
            source={require('@assets/Clock.png')}
            style={{
              height: '60%',
              width: '100%'
            }}
            resizeMode="contain"
          >
            <Image
              style={{
                marginTop: '4.5%',
                alignSelf: 'center',
                height: '30%',
                width: '100%'
              }}
              resizeMode="contain"
              source={require('@assets/Needle.png')}
            />
          </ImageBackground>
        </View>
      </View>
    )
  }
}

Clock

Upvotes: 9

Sten Muchow
Sten Muchow

Reputation: 6701

Same as you would handle this in regular old html,css.

Use position:absolute then align the items so that they match how you expect.

Upvotes: 0

Related Questions