3

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

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

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

在此处输入图像描述

下面是我尝试过的代码。

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

1 回答 1

2

类似问题

请注意,对象的xy坐标layout是相对于使用组件的直接父组件的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>
于 2020-12-26T04:16:44.850 回答