React-Native :React Native 可以找出每个设备的确切绝对位置吗?

问题描述

我想使用绝对位置在图像上显示文本。 但是,由于每个设备的屏幕尺寸不同,因此很难确定确切的位置。

有没有办法计算准确的位置?

我发布了一个类似的问题,但没有得到我想要的答案。 my first question

enter image description here

下面是我试过的代码

 <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>

解决方法

similar issue

请注意,x 对象的 ylayout 坐标是相对于使用 onLayout 的组件的直接父组件的。在您的情况下,ImageBackground 的布局是相对于立即包装它的任何内容进行的。

像这样放置 Text 的可能解决方案是组合树,例如

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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...