오늘은 안드로이드 화면에서 터치를 했을때 안드로이드에서 좌표를 어떻게 인식하는지 알아보는 과정을 가지겠습니다. 응용을 하게되면 그림그리기와 같은 앱도 만들 수 있겟죠? 먼저 저희가 다룰 이벤트는 Touch 이벤트 입니다. 저희가 터치를 하고 드래그를 하면서 움직일때 모든 동작들을 인식하게 될 텐데요 먼저 화면을 그려보죠. activity_main.xml
윗 부분은 저희가 터치를 할 영역이고 아래 영역은 터치한 영역의 좌푯값을 출력해줄 영역입니다. 보기 쉽게 간단하게 구분해 주는게 좋겠죠? MainActivity.java
정확히 어디를 터치하는지 표시해 주는 결과를 확인할 수 있습니다. 티스토리 뷰injunech 2017. 2. 21. 21:15 View 절대 좌표값 구하는 방법 View.getLocatioinOnScreen(int[]); 위와 같은 함수를 사용하면 전체 스크린상의 절대 위치의 좌표를 구할수 있다. 예시로 아래와 같이 사용하면 된다. public boolean chkTouchInside(View view, int x, int y) { int[] location = new int[2]; view.getLocationOnScreen(location); if (x >= location[0]) { if (x <= location[0] + view.getWidth()) { if (y >= location[1]) { if (y <= location[1] + view.getHeight()) { return true; } } } } return false; } 티스토리 뷰out of coding 2014. 11. 25. 13:39 화면상에 View가 그려지게 되면, 그 크기를 구할수가 있게 된다. 이 부분들은 두가지로 구분이 되게 되는데, 다음과 같다. 1. parent에 대한 자신의 위치 (상대위치) - getLeft(), getRight(), getTop(), getBottom() - 그냥 단순하게 위의 네가지 함수를 사용하면 구할수 있게 된다. 2. 화면상의 자신의 위치 (절대위치) - getLocationOnScreen() - 사용방법 int[] location = new int[2]; view.getLocationOnScreen(location); 3. 응용 - touch event가 해당 view에서 발생하였는지 알아내는 방법. public boolean isTouchInside(View view, int x, int y) { int[] location = new int[2]; view.getLocationOnScreen(location); final int realRight = location[0] + view.getWidth(); final int realBottom = location[1] + view.getHeight(); final boolean result = (x >= location[0] && x <= realRight && y >= location[1] && realBottom); return result; } 티스토리 뷰devbible 2011. 10. 24. 22:26 Android 에서는 이런저런 이유로 view의 위치값을 필요로 한다. 1. 함수이용 View.getGlobalVisibleRect(Rect) 을 이용해서 좌표를 구해올수있다. Global이라고해도 스크린상의 절대좌표는 아니고. 해당 RootView 레이아웃을 기준으로한 좌표다. 2. 직접계산 그래서 view.getRootView() 와 view.getParentView() 를 이용하여 수동으로 절대값X,Y를 구할 수 있다. View parentView = view.getRootView(); int sumX = 0; int sumY = 0; boolean chk = false; view = (View) view.getParent(); 3. 솔찍히 위에 방법 다 필요없고 더 정확하다 이거하나면 된다. 1,2번은 쓰지말기를. View.getLocatioinOnScreen(int[]); 이러면 뷰가 스크린상 위치하는 좌표를 알 수 있다. TouchEvent에서 들어온 x,y 좌표들과 동일한 체계가 된다. 그래서 예를 들어 TouchEvent 해당 View안에서 일어났는지 알기위해서는 이런코드면된다. public boolean chkTouchInside(View view, int x, int y) { int[] location = new int[2]; view.getLocationOnScreen(location); if (x >= location[0]) { if (x <= location[0] + view.getWidth()) { if (y >= location[1]) { if (y <= location[1] + view.getHeight()) { return true; } } } } return false; } [작성자] devbible.tistory.com |