屏幕坐标用法总结

获得当前view在屏幕的坐标

final int[] location = new int[2];   
view.getLocationOnScreen(location);  
int x = location[0]  ; 
int y = location[1]  ;
     

这样就可以得到该视图在全局坐标系中的x,y值(注意这个值是要从屏幕顶端算起,也就是说包括了通知栏的高度).

获得相对在它父布局里的坐标

View.getLeft() ;
View.getTop() ;
View.getBottom();
View.getRight() ; 
View.getX() ; 
View.getY() ; 
     

这些都是相对坐标,例如如果在一个Button外面加一个RelativeLayout,让RelativeLayout宽高是wrap_content, 这样RelativeLayout的大小和Button一样,不管这个RelativeLayout放在窗口的哪里Button.getY()的值都是0.

top是左上角纵坐标,left是左上角横坐标,right是右下角横坐标,bottom是右下角纵坐标。而x,y是左上角横纵坐标,是android 3.0之后加入的, 也是相对于父容器的坐标。

注意:View.getX() ; 要区分于MotionEvent.getRawX(); 和MotionEvent.getX(); 在public boolean onTouch(View view, MotionEvent event) 中,当你触到控件时,x,y是相对于该控件左上点(控件本身)的相对位置。 而rawx,rawy始终是相对于屏幕的位置。getX()是表示Widget相对于自身左上角的x坐标,而getRawX()是表示相对于屏幕左上角的x坐标值 (注意:这个屏幕左上角是手机屏幕左上角,不管activity是否有titleBar或是否全屏幕)。

《屏幕坐标用法总结》

View.getLocationInWindow()和 View.getLocationOnScreen()的区别

View.getLocationInWindow()和 View.getLocationOnScreen()在window占据全部screen时,返回值相同,不同的典型情况是在Dialog中时。 当Dialog出现在屏幕中间时,View.getLocationOnScreen()取得的值要比View.getLocationInWindow()取得的值要大。

getTop()和getY()的区别

一般情况下getTop()和getY()返回值是一样的。查看源码:

public final int getTop() {
    return mTop;
}
public float getY() {
    return mTop + getTranslationY();
}
    /** * The vertical location of this view relative to its {@link #getTop() top} position. * This position is post-layout, in addition to wherever the object's * layout placed it. * * @return The vertical position of this view relative to its top position, * in pixels. */
    @ViewDebug.ExportedProperty(category = "drawing")
    public float getTranslationY() {
        return mRenderNode.getTranslationY();
    }
     

getY的值是getTop+getTranslationY,这个getTranslationY是自己相对自己顶部的偏移。 可以通过setTranslationY(int mTranslationY) ;设置偏移,默认为0.

获得状态栏和标题栏高度

首先要知道Rect表示一个矩形,可以得到左上和右下角坐标:

《屏幕坐标用法总结》

Rect rect = new Rect();
//getWindow().getDecorView()得到的View是Window中的最顶层View,可以从Window中获取到该View,
//然后该View有个getWindowVisibleDisplayFrame()方法可以获取到程序显示的区域,
//包括标题栏,但不包括状态栏。
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
//1.获取状态栏高度:
//根据上面所述,我们可以通过rect对象得到手机状态栏的高度
int statusBarHeight = rect.top;
//2.获取标题栏高度:
getWindow().findViewById(Window.ID_ANDROID_CONTENT);
//该方法获取到的View是程序不包括标题栏的部分,这样我们就可以计算出标题栏的高度了。
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight = contentTop - statusBarHeight
     
    原文作者:mxn原创
    原文地址: http://souly.cn/%E6%8A%80%E6%9C%AF%E5%8D%9A%E6%96%87/2015/11/24/%E5%B1%8F%E5%B9%95%E5%9D%90%E6%A0%87%E7%94%A8%E6%B3%95%E6%80%BB%E7%BB%93/
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞