1.android坐标系
屏幕的左上角顶点作为坐标系原点,向左,向下为正方向。
Android坐标系
View.getLocationInWindow(int[] location)一个控件在其父窗口中的坐标位置
//View#getLocationInWindow
public void getLocationInWindow(int[] location) {
if (location == null || location.length < 2) {
throw new IllegalArgumentException("location must be an array of two integers");
}
if (mAttachInfo == null) {
// When the view is not attached to a window, this method does not make sense
location[0] = location[1] = 0;
return;
}
float[] position = mAttachInfo.mTmpTransformLocation;
position[0] = position[1] = 0.0f;
if (!hasIdentityMatrix()) {
getMatrix().mapPoints(position);
}
position[0] += mLeft;
position[1] += mTop;
ViewParent viewParent = mParent;
while (viewParent instanceof View) {
final View view = (View) viewParent;
position[0] -= view.mScrollX;
position[1] -= view.mScrollY;
if (!view.hasIdentityMatrix()) {
view.getMatrix().mapPoints(position);
}
position[0] += view.mLeft;
position[1] += view.mTop;
viewParent = view.mParent;
}
if (viewParent instanceof ViewRootImpl) {
// *cough*
final ViewRootImpl vr = (ViewRootImpl) viewParent;
position[1] -= vr.mCurScrollY;
}
location[0] = (int) (position[0] + 0.5f);
location[1] = (int) (position[1] + 0.5f);
}
View.getLocationOnScreen(int[] location) 一个控件在其整个屏幕上的坐标位置
//View#getLocationOnScreen
public void getLocationOnScreen(int[] location) {
getLocationInWindow(location);
final AttachInfo info = mAttachInfo;
if (info != null) {
location[0] += info.mWindowLeft;
location[1] += info.mWindowTop;
}
}
2.View坐标系
View坐标系与Android 坐标系并不冲突。
View自身坐标
View提供的API
•getTop():获取View顶边到其父布局顶边的距离
•getLeft():获取View左边到其父布局左边的距离
•getRight():获取View右边到其父布局左边的距离
•getBottom():获取View底边到其父布局顶边的距离
根据上图得到的数据,我们可以计算出View的宽高。View源码中getHeight()和getWidth()也是使用相同方法实现的,如下:
@ViewDebug.ExportedProperty(category = "layout")
public final int getWidth() {
return mRight - mLeft;
}
@ViewDebug.ExportedProperty(category = "layout")
public final int getHeight() {
return mBottom - mTop;
}
假设圆点是我们的触摸点,它会激活相应的触摸事件
触摸后的坐标
• getX():获取点击位置离View左边的距离
• getY():获取点击位置离View顶边的距离
• getRawX():获取点击位置离屏幕左边的距离
• getRawY():获取点击位置离屏幕顶边的距离














网友评论