簡體   English   中英

如何獲取視圖的 x & Y 坐標

[英]How to get the x & Y coordinates of a view

我已經在我的布局中放置了一個圖像視圖,現在我需要知道它的 x & y 坐標來動態地在它上面繪制一些東西。

在此處輸入圖像描述

我試過imageView.getTop(); & imageView.getY()但它們都返回“0”,但圖像不是從“0”開始,從開始有一些余量,從頂部有很大余量。

有沒有其他方法可以得到這個。

嘗試使用 imageView.getLocationOnScreen(int[]) 來獲取視圖相對於其父/屏幕的 X 和 Y:

int[] positions = new int[2];
imageView.getLocationOnScreen(positions);
int x = positions[0];
int y = positions[1];

為確保視圖有機會更新,請在使用 view.post 計算出視圖的新布局后運行您的位置請求:

view.post {
    val point = IntArray(2)
    view.getLocationOnScreen(point)
    val (x, y) = point
}

值不應再為 0,但我對華為設備有不好的體驗。 獲取 x 和 y 坐標的其他方法是使用 viewTreeObserver

view.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                view.viewTreeObserver.removeOnGlobalLayoutListener(this)      
                val point = IntArray(2)
                view.getLocationOnScreen(point)
                val (x, y) = point
            }
});

使用這種方法,您可能會遇到一些視覺故障

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM