在 Android 上,AbsoluteToLocal 方法可能会返回错误的值,需要使用其他方法计算。代码示例如下:
// 获取本地坐标系
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float density = displayMetrics.density;
float xdpi = displayMetrics.xdpi;
float ydpi = displayMetrics.ydpi;
float scaledDensity = displayMetrics.scaledDensity;
Rect rect = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
float statusBarHeight = rect.top / density;
// 计算绝对坐标转为本地坐标
float[] location = new float[2];
view.getLocationOnScreen(location);
float x = (location[0] - rect.left) / density;
float y = (location[1] - rect.top - statusBarHeight) / density;
float localX = (x / xdpi) * 25.4f;
float localY = (y / ydpi) * 25.4f;