안드로이드 ImageView 좌표 설정 - andeuloideu ImageView jwapyo seoljeong

오늘은 안드로이드 화면에서 터치를 했을때  안드로이드에서 좌표를 어떻게 인식하는지

알아보는 과정을 가지겠습니다. 응용을 하게되면 그림그리기와 같은 앱도 만들 수 있겟죠? 

먼저 저희가 다룰 이벤트는 Touch 이벤트 입니다. 

저희가 터치를 하고 드래그를 하면서 움직일때 모든 동작들을 인식하게 될 텐데요 먼저 화면을 그려보죠.

activity_main.xml




    
    

    

        
        
    

윗 부분은 저희가 터치를 할 영역이고

아래 영역은 터치한 영역의 좌푯값을 출력해줄 영역입니다.

보기 쉽게 간단하게 구분해 주는게 좋겠죠?

안드로이드 ImageView 좌표 설정 - andeuloideu ImageView jwapyo seoljeong

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.gesture.GestureOverlayView;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    //객체 선언
    View view1, view2;
    ScrollView scrollView1;
    TextView textView1;
    GestureDetector detector; //무슨 제스쳐를 했는지 감지

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //객체 초기화
        view1 = findViewById(R.id.view1);
        scrollView1 = findViewById(R.id.scrollView1);
        textView1 = findViewById(R.id.textView1);

        //터치를 했을때 작동하는 메서드
        view1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                float curX = event.getX();  //눌린 곳의 X좌표
                float curY = event.getY();  //눌린 곳의 Y좌표

                if(action == event.ACTION_DOWN) {   //처음 눌렸을 때
                    printString("손가락 눌림 : " + curX + ", " + curY);
                } else if(action == event.ACTION_MOVE) {    //누르고 움직였을 때
                    printString("손가락 움직임 : " + curX + ", " + curY);
                } else if(action == event.ACTION_UP) {    //누른걸 뗐을 때
                    printString("손가락 뗌 : " + curX + ", " + curY);
                }
                return true;
            }
        });
    }

    private void printString(String s) {
        //좌표 출력
        textView1.append(s + "\n"); //한 줄씩 추가

        //자동으로 마지막 줄로 스크롤 내림
        scrollView1.fullScroll(View.FOCUS_DOWN);
    }
}

정확히 어디를 터치하는지 표시해 주는 결과를 확인할 수 있습니다.

티스토리 뷰

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의 위치값을 필요로 한다.
그래서 있는것이 view.getLeft(), view.getRight(), view.getTop(), view.getBottom() 이다.(좌,우,상,하)
하지만 이것은 상위Layout에서 해당 view가 위치하는 값이므로 상대값이지 절대값이 아니다.
또한 터치나 제스처에서는 X , Y 값을 받지만 이것또한 절대값이 아니다.
이벤트에서 rawX, rawY 를 구할 수도있지만,  항상 절대값은 아니다.

1. 함수이용

View.getGlobalVisibleRect(Rect) 을 이용해서 좌표를 구해올수있다.

Global이라고해도 스크린상의 절대좌표는 아니고. 해당 RootView 레이아웃을 기준으로한 좌표다.

2. 직접계산

그래서 view.getRootView() 와 view.getParentView() 를 이용하여 수동으로 절대값X,Y를 구할 수 있다.
아래 코드는 오래전 작성해놓은것이지만....

  public void toViewRawXY(View view){
  View parentView = view.getRootView();
  int sumX = 0;
  int sumY = 0;

  boolean chk = false;
  while (!chk) {
   sumX = sumX + view.getLeft();
   sumY = sumY + view.getTop();

   view = (View) view.getParent();
   if(parentView == view){
    chk = true;
   }
  }
  android.util.Log.d("","rawX : "+sumX);
  android.util.Log.d("","rawY : "+sumY);
 }

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