Question

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;
        }

    });
Was it helpful?

Solution

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.

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top