使用OnTouch是如何,我可以检查图像感动()图像、OnTouch

2023-09-07 11:45:08 作者:蓄势待发

我想获得的X,Y坐标上的图像的触摸和我想执行一些动作。那么,谁能告诉我怎么走了X,Y坐标图像的时候才感动。在此先感谢。

I am trying to get the x,y co-ordinates on Touch of Image and on that I want to perform some action. So, can anyone tell me how to get the x,y co-ordinates of Image when it is touched. Thanks In Advance.

我的code -

public class MovableObject extends ImageView implements OnTouchListener{

    Bitmap myBmp;
    Paint myPaint = new Paint();
    int MoveX = 0;

    public MovableObject(Context context,int moveObject,Bitmap myBmp) {
        super(context);
        super.setClickable(true);
        this.myBmp = myBmp;
        myPaint.setColor(Color.WHITE);
        this.MoveX = moveObject;
        setOnTouchListener(this);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(myBmp, MoveX, 100, myPaint);
    }
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction() & MotionEvent.ACTION_MASK) {

            case MotionEvent.ACTION_DOWN:
                System.out.println("down...."+event.getX()+" "+event.getY());
            case MotionEvent.ACTION_MOVE:
        }
        return true;
    }
}

通过这个我收到的X,Y坐标,我点击,但我想要得到的X,Y,当我点击我的图片。

推荐答案

我找到了另一种方式,我认为它使用的矩形

I found another way and I think its a best way to detect touch for any view by using Rect

我刚刚创建一个返回矩形的实例,包括所有四个坐标视图的方法

I just created a method that returns Rect instance including all the four co-ordinates of a view

   private Rect getLocationOnScreen(View mView) {
        Rect mRect = new Rect();
        int[] location = new int[2];

        mView.getLocationOnScreen(location);

        mRect.left = location[0];
        mRect.top = location[1];
        mRect.right = location[0] + mView.getWidth();
        mRect.bottom = location[1] + mView.getHeight();

        return mRect;
    }

,然后简单地覆盖的onTouchEvent(MotionEvent事件)在你的活动,并检查是否有认为要检测被触摸或没有,

And then simply override onTouchEvent(MotionEvent event) in your Activity and check for the co-ordinates of any view that you want to detect is touched or not,

@Override
public boolean onTouchEvent(MotionEvent event) {
     int x = (int) event.getX();
     int y = (int) event.getY();

     if (event.getAction() == MotionEvent.ACTION_DOWN &&
                                      getLocationOnScreen(imageview).contains(x, y)) {
          Toast.makeText(getApplicationContext(), 
                                          "ImageView Touched", Toast.LENGTH_LONG).show();
     }
    return super.onTouchEvent(event);
}
 
精彩推荐
图片推荐