简体   繁体   中英

How to get x,y coordinates of an imageview on different devices and densities in Android

I am new with this so.. if I have an imageview on different devices 10' tablet 7' tablet and a mobile of 5' with different densities.

How I am going to get the corresponding x,y with a touch event what are the "rules" here?

thank you

The image is for example a flower when touching a petal of the flower on the imageview the position of x,y are the same in all densities and sizes?

You can easily get coordinate of a view from touch point by using touch listener methid like this,

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final ImageView imageView = findViewById(R.id.imageView);
    imageView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
           Log.d("Tag", "X,Y : " + event.getX() + "," + event.getY());
           return true;
        }
    });
}

You could also use the width and height of ImageView , that is what changes in different densities. And then ask for percentages of the image, ie, for example, the half up or the fourth part down. (75% of 1024 is 1024*0.75)

@Override
public boolean onTouch(View v, MotionEvent event) {

    int maxX = v.getWidth();
    int maxY = v.getHeight();

    int x = (int) event.getX();
    int y = (int) event.getY();

    if (action == MotionEvent.ACTION_DOWN) {
        if (x > (maxX * 0.25) && x < (maxX * 0.50) && y > (maxY * 0.25) && y < (maxY * 0.50)) {
            Log.i("Tag", "You pressed an area");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM