Search code examples
javaandroidcanvaspaintrectangles

Detect touch on rectangle that are using drawRect()


I am refering to this tutorial to make a resizable rectangle. But in my case, I need more than that.

I need to drag and move the rectangle as well without touching on the point. Is this possible? Which part of the code should I change?

Or is there any way to detect the rectangle that is drawn by using drawRect()?

Thanks.


Solution

  • Use the x and y coordinates of the click event and detect if this position is in the rectangle.

    yourView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN){
                    int x = event.getX();
                    int y = event.getY();
                    if(x > rectLeftX && x < rectRightX && y > rectBottomY && y < rectTopY){
                        /* Trigger your action here */
                    }
                }
                return true;
            }
        });