简体   繁体   English

如何获取视图的 x & Y 坐标

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

I have placed an image view in my layout, now i need to know its x & y coordinates to draw some stuff over it dynamically.我已经在我的布局中放置了一个图像视图,现在我需要知道它的 x & y 坐标来动态地在它上面绘制一些东西。

在此处输入图像描述

I tried imageView.getTop();我试过imageView.getTop(); & imageView.getY() but they both return "0", but the image is not starting from "0" there is some margin from start and much margin from top. & imageView.getY()但它们都返回“0”,但图像不是从“0”开始,从开始有一些余量,从顶部有很大余量。

Is there any other way to get this.有没有其他方法可以得到这个。

Try with imageView.getLocationOnScreen(int[]) to get X and Y of a view relative to its parent/screen:尝试使用 imageView.getLocationOnScreen(int[]) 来获取视图相对于其父/屏幕的 X 和 Y:

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

To ensure view has had a chance to update, run your location request after the View's new layout has been calculated by using view.post:为确保视图有机会更新,请在使用 view.post 计算出视图的新布局后运行您的位置请求:

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

Values SHOULD no longer be 0 but i had bad experiences with huawei devices.值不应再为 0,但我对华为设备有不好的体验。 Other way to get x and y coordinates is using viewTreeObserver获取 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
            }
});

Possibly you experience some visual glitch with this approach使用这种方法,您可能会遇到一些视觉故障

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM