Home > database >  where does the position in react-native start from when we use measure inside onLayout?
where does the position in react-native start from when we use measure inside onLayout?

Time:10-29

In react-native when I am trying to get position of a element relative to the screen size. I use measure in OnLayout. What I want to know is if the position pageX that is returned is based on center of the element or from the top of the element.

<View
 onLayout={(event) => {
  event.target.measure((x, y, width, height, pageX, pageY) => {
  console.log(pageX) // Eg. 320
  console.log(pageY) // Eg. 100
 })
}}>
<Text>lorem ipsum</Text>
</View>

Lets say I get the pageX of a circle which is 320.


Is pageX 320 the top of the element?
enter image description here


or is pageX 320 the center of the element?
enter image description here

CodePudding user response:

PageX indicates the distance of the element to the left of the screen and PageY indicates the distance from the top of the screen. This measurement is made relative to the left and top of the element, not the center.

import { TouchableOpacity, View, } from "react-native"
import React, { useRef } from "react"


export default function Screen() {

    const circleRef = useRef()

    const onPress = () => {
        console.log(circleRef.current.measure(
            (x, y, width, height, pageX, pageY) => {
                console.log({ width, height, pageX, pageY })
                // output: {"height": 100, "pageX": 75, "pageY": 50, "width": 100}
            }))
    }

    return (
        <TouchableOpacity onPress={onPress}>
            <View
                style={{
                    width: 100,
                    height: 100,
                    marginTop: 50, // pageY = 50
                    marginLeft: 75, // pageX = 75
                    borderRadius: 99,
                    backgroundColor: "#000"
                }}
                ref={circleRef}
            />
        </TouchableOpacity>
    )
}

  • Related