Evian Pringle
Evian Pringle

Reputation: 45

How to detect a touch event when the user touches a shape that has a diagonal side

I have a view where I have drawn a path on the canvas. The path drawn contains the x and y coordinates to draw the shape. The shape has 2 diagonal sides. What I need to do is to detect when a user touches either one of these diagonal sides. I am able to detect when a user touches a vertical and horizontal side of the shape but I am having trouble finding out how to do the same for the diagonal lines in a path.

I was able to determine whether a horizontal or vertical line was touched just by simply knowing the x and y values of each end of the line and checking if the user touched the screen within these values. However, the same approach cannot be done for a diagonal line so I am wondering how I would approach this.

Here is an image of the shape I have drawn with its coordinates:

Image of Shape

onTouchEvent Method:

@Override
public boolean onTouchEvent(MotionEvent ev) {
                //The Top is touched
                if ((ev.getX() >= x1 && ev.getX() <= x2 && ev.getY() >= y1 && ev.getY() <= y1)) {
                    Toast.makeText(this.getContext(), "Top Touched", Toast.LENGTH_SHORT).show();
                }
                //The Bottom is touched
                else if ((ev.getX() >= x4 && ev.getX() <= x3 && ev.getY() >= y3 && ev.getY() <= y3)) {
                    Toast.makeText(this.getContext(), "Bottom Touched", Toast.LENGTH_SHORT).show();
                }
                //The Left Side is touched
                else if ((ev.getY() >= y2 && ev.getY() <= y3 && ev.getX() >= x4 && ev.getX() <= x4)) {
                    Toast.makeText(this.getContext(), "Left Side Touched", Toast.LENGTH_SHORT).show();                       
                }
                //The Right Side is touched
                else if ((ev.getY() >= y2 && ev.getY() <= y3 && ev.getX() >= x3 && ev.getX() <= x3)) {
                    Toast.makeText(this.getContext(), "Right Side Touched", Toast.LENGTH_SHORT).show();
                    }

Upvotes: 0

Views: 280

Answers (1)

clzd0792
clzd0792

Reputation: 66

} else if ((ev.getX() < x1 && ev.getY() < y2) && 
    (ev.getX() - x4 = (ev.getY - y1) * ((x1-x4)/(y2-y1))) {
    Toast.makeText(this.getContext(), "Left Top 
        Touched",Toast.LENGTH_SHORT).show();
} else if ((ev.getX() > x2 && ev.getY() < y2) &&
    (ev.getX() - x2 = (ev.getY - y1) * ((x3-x2)/(y2-y1)) {
    Toast.makeText(this.getContext(), "Right Top Touched", 
        Toast.LENGTH_SHORT).show();
}

Upvotes: 1

Related Questions