reactjsreact-nativeimagebackground

React-Native : Can react native find out the exact absolute position for each device?


I want to show text on image using absolute position. However, it is difficult to determine the exact position because the screen size is different for each device.

Is there a way to calculate the exact position?

I posted a similar question, but I didn't get the answer I wanted. my first question

enter image description here

Below is the code I've tried.

 <ImageBackground
      source={require("../../assets/brain/ohi.png")}
      style={{ width: "100%", height: "100%", position: "relative" }}
      resizeMode="contain"
      onLayout={(event) => this.setLayout(event.nativeEvent.layout)}
    >
      <Text
        style={{
          position: "absolute",
          left: windowWidth * 0.22,
          top: windowHeight * 0.4,
        }}
      >
        Text_1
      </Text>
      <Text
        style={{
          position: "absolute",
          left: 280,
          top: 300,
        }}
      >
        Text_2
      </Text>
    </ImageBackground>

Solution

  • See similar issue.

    Note that the x and y coordinates of the layout object are relative to the immediate parent component of the component where onLayout is used. In your case, ImageBackground's layout is taken relative to whatever immediately wraps it.

    A possible solution to place Text like so is a composition tree such as

    const [layout, setLayout] = useState();
    
    <View style={{position: 'relative'}}>
      <Image width={200} height={200} onLayout={event => setLayout(event.nativeEvent.layout)} />
      
      <Text style={{position: 'absolute', top: (layout?.y || 20) + 20, left: (layout?.x || 30) + 30}} />
    </View>