我试图找到用户仅在图像视图内触摸的坐标。
到目前为止,我已经通过以下代码设法做到了这一点:
img = (ImageView) findViewById(R.id.image);
img.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
x = (int) event.getX();
y = (int) event.getY();
int[] viewCoords = new int[2];
img.getLocationOnScreen(viewCoords);
int imageX = (int) (x - viewCoords[0]); // viewCoods[0] is the X coordinate
int imageY = (int) (y - viewCoords[1]); // viewCoods[1] is the y coordinate
text.setText("x:" +x +"y"+y);
return false;
}
});
然而这是 onTouchListener 这意味着它只在每次触摸后找到坐标,我想做的是创建它,以便在用户在图像视图周围移动手指时不断找到坐标。我通过这段代码在整个屏幕上实现了这一点:
@Override
public boolean onTouchEvent(MotionEvent event) {
x = (float)event.getX();
y = (float)event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
}
text.setText("x:"+ x +" y:" +y);
return false;
}
但是我不知道如何使此代码仅在 imageview 内工作。