Detect touch on bitmap

You should work with something like so:

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

    switch(action){
    case MotionEvent.ACTION_DOWN:
        if (x >= xOfYourBitmap && x < (xOfYourBitmap + yourBitmap.getWidth())
                && y >= yOfYourBitmap && y < (yOfYourBitmap + yourBitmap.getHeight())) {
            //tada, if this is true, you've started your click inside your bitmap
        }
        break;
    }
}

That’s a start, but you need to handle case MotionEvent.ACTION_MOVE and case MotionEvent.ACTION_UP to make sure you properly deal with the user input. The onTouchEvent method gets called every time the user: puts a finger down, moves a finger already on the screen or lifts a finger. Each time the event carries the X and Y coordinates of where the finger is. For example if you want to check for someone tapping inside your bitmap, you should do something like set a boolean that the touch started inside the bitmap on ACTION_DOWN, and then check on ACTION_UP that you’re still inside the bitmap.

Leave a Comment