问题描述
我想使用绝对位置在图像上显示文本。 但是,由于每个设备的屏幕尺寸不同,因此很难确定确切的位置。
有没有办法计算准确的位置?
我发布了一个类似的问题,但没有得到我想要的答案。 my first question
下面是我试过的代码。
<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>
解决方法
请注意,x
对象的 y
和 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>