如何获取视图的 x 和 Y 坐标
How to get the x & Y coordinates of a view
我已经在我的布局中放置了一个图像视图,现在我需要知道它的 x 和 y 坐标才能在其上动态绘制一些东西。
我尝试了 imageView.getTop();
和 imageView.getY()
但它们都是 return“0”,但图像不是从“0”开始的顶.
还有其他方法可以得到吗
尝试使用 imageView.getLocationOnScreen(int[]) 获取视图相对于其 parent/screen 的 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
}
});
可能您在使用这种方法时遇到了一些视觉故障
我已经在我的布局中放置了一个图像视图,现在我需要知道它的 x 和 y 坐标才能在其上动态绘制一些东西。
我尝试了 imageView.getTop();
和 imageView.getY()
但它们都是 return“0”,但图像不是从“0”开始的顶.
还有其他方法可以得到吗
尝试使用 imageView.getLocationOnScreen(int[]) 获取视图相对于其 parent/screen 的 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
}
});
可能您在使用这种方法时遇到了一些视觉故障