Get Touch Coordinates Relative To A View (ScreenToClient Equivalent?)

前端 未结 3 1571
悲哀的现实
悲哀的现实 2021-02-01 20:09

I have an image I am displaying to a user in my android application.

I want to be able to tell where they \'touch\' the image.

I can easily get the screen coordi

3条回答
  •  感情败类
    2021-02-01 20:26

    I have just had the same problem, and trying the DeeV solution I always got 0 from both getLeft() and getTop() methods. As changing the layout wasn't an option (because I think that getTop/Left are relative only to the view's parent) I had to figure out how to get the absolute position of the view.

    Here is a similar approach using getLocationOnScreen(location):

    protected Point getRelativePosition(View v, MotionEvent event) {
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        float screenX = event.getRawX();
        float screenY = event.getRawY();
        float viewX = screenX - location[0];
        float viewY = screenY - location[1];
        return new Point((int) viewX, (int) viewY);
    }
    

提交回复
热议问题