Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkin if pressed inside rectF in onTouchEvent

I've been working on a very simple little application using an extended view. The problem is that i can't find what been pressed in my onTouchEvent. I've understood that i've to compare the pressure-points (x and y) to the elements and see which one it could be.

But... I've declared a rectangle using:

Paint color= new Paint();
color.setColor(Color.BLACK);
rectF = new RectF(0.0f, 0.0f, 1.0f, 0.5f) ;
canvas.drawRect(rectF, color);

So far so good, but in the onTouchEvent function

public boolean onTouchEvent(MotionEvent event) {
    int action = event.getAction() ;
    float x = event.getX() ;
    float y = event.getY() ;

    switch(action) {
    case MotionEvent.ACTION_DOWN:

        if(rectF().contains(x, y)) {
            // Something should happen
        }

    }

    invalidate();
    return true ;
}

I set the rectF with some kind of relative points ranging from 0-1, but the X and Y i get from the event ranges from 0 and upwards depending on screen-size.

Can I easily convert either of the values?

Edit

Thought someone was interested in the final solution...

public boolean onTouchEvent(MotionEvent event) {
    int action = event.getAction() ;
    float x = event.getX() ;
    float y = event.getY() ;

    int width = this.getWidth() ;
    int height = this.getHeight() ;

    switch(action) {
    case MotionEvent.ACTION_DOWN:

        if(rectF().contains(x/width, y/height)) {
            // Something should happen
        }

    }

    return true ;

}   
like image 269
dubbe Avatar asked Nov 05 '22 09:11

dubbe


1 Answers

The values of the touch point and the RectF have to be on the same reference scale in oreder to be compared properly. Meaning that if you declare your RectF to use relative sizes (0-1) you will either need to :

1: normalize the MotionEvent position by your screen size

OR 2: "denormalize" the RectF dimensions by your actual screen size.

I think 1 is generally preferrable as it lets you define your rects in terms of relative layout, independent of the actual screen size and convert the event positions on-the-fly.

like this : rectF.contains(x/screenWidth, y/screenHeight);

You can retrieve the screen dimensions by calling
Display display = getWindowManager().getDefaultDisplay() in your Activity and then calling display.getWidth() or display.getHeight()

like image 97
kostja Avatar answered Nov 09 '22 05:11

kostja