3

I have an image view that I draw my game board in for my game. I need to get the X, Y of the touch relative to the image view. For example: If someone touched the very top left Pixel, it would return (0,0) or, say the game board was a 100,100 board, and I touched right in the middle I would get (50,50)...How would one do this?

 gameView.setOnTouchListener(new OnTouchListener(){

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN){
            int x = (int) event.getX() / pieceSize;
            int y = (int) event.getY() / pieceSize;
            Log.d("Touch Event", "Touch event at "+ x + " " +y);

            doMove(x, y);

            Log.d("Move", "The move was " + doMove(x,y));
            }
            gameView.setImageBitmap(Draw(pieceSize));

            return true;
        }

    });
Aaron Decker
  • 559
  • 9
  • 25

3 Answers3

5

You can use

onTouch(View v, MotionEvent event)

Called when a touch event is dispatched to a view.

And retrieve x and y from the event object.

Of course, by setting an OnTouchListener on the view you are working on.

ChristopheCVB
  • 7,269
  • 1
  • 29
  • 54
0

if you've put a touch listener onto the ImageView, then event.getX() and event.getY() should return values that are relative to the ImageView.

elijah
  • 2,904
  • 1
  • 17
  • 21
0

You should set OnTouchListener and getX and getY of the event. Lots of answers on this one. For example hereA: Get the co-ordinates of a touch event on Android

Community
  • 1
  • 1
Michał Klimczak
  • 12,674
  • 8
  • 66
  • 99