Aaron Decker
Aaron Decker

Reputation: 558

Detecting touch in Image View

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

    });

Upvotes: 3

Views: 8676

Answers (3)

Michał Klimczak
Michał Klimczak

Reputation: 13144

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

Upvotes: 0

elijah
elijah

Reputation: 2924

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.

Upvotes: 0

ChristopheCVB
ChristopheCVB

Reputation: 7305

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.

Upvotes: 5

Related Questions