zoukankan      html  css  js  c++  java
  • android学习8——获取view在屏幕上的绝对坐标

    获取view在屏幕上的绝对坐标在调试时候非常有用.
    看如下代码

    public class AbsolutePosActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(new DrawLineView(this));
        }
    }
    public class DrawLineView extends View {
        @Override
        protected void onDraw(Canvas canvas) {
            Paint paint = new Paint();
            paint.setColor(Color.WHITE);
            canvas.drawLine(0, 0, 1536, 2048, paint);
            super.onDraw(canvas);
            int[] location = new int[2];
            getLocationOnScreen(location);
            Log.i("Logzy", "x=" + location[0] + ",y=" + location[1]);
            Log.i("Logzy", "width=" + getWidth() + ",height=" + getHeight());
        }
        public DrawLineView(Context context) {
            super(context);
        }
    }
    

    界面显示如下所示:

    日志输入为:

    01-06 07:55:00.552  24762-24762/edu.cgxy.absolutepos I/Logzy﹕ x=0,y=146
    01-06 07:55:00.552  24762-24762/edu.cgxy.absolutepos I/Logzy﹕ width=720,height=1134
    

    getLocationOnScreen得到了view左上角的坐标,单位是像素.
    用以下代码去掉标题栏.

    public class AbsolutePosActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(new DrawLineView(this));
        }
    }
    

    界面显示如下所示:

    日志输入为:

    01-06 07:59:42.608  25290-25290/edu.cgxy.absolutepos I/Logzy﹕ x=0,y=0
    01-06 07:59:42.608  25290-25290/edu.cgxy.absolutepos I/Logzy﹕ width=720,height=1280
    

    可以看到没有标题栏.view的左上解绝对坐标就是(0,0)
    源代码地址:https://github.com/zhouyang209117/AndroidTutorial/tree/master/Game/ch4/AbsolutePos

  • 相关阅读:
    IDEA使用Git传放项目
    前端自适应知识点
    数据可视化
    vue调用Moment显示时间
    java判断通常的逻辑
    java常用的逻辑
    java匿名内部类练习
    java 匿名内部类
    java 内部类定义在局部时需要注意的情况
    java内部类的定义原则
  • 原文地址:https://www.cnblogs.com/zhouyang209117/p/5104311.html
Copyright © 2011-2022 走看看