Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect touch on bitmap

Tags:

android

Greets,

Does anyone how I go about detecting when a user presses on a bitmap which is inside a canvas?

Thanks

like image 215
Steve Avatar asked Mar 15 '10 13:03

Steve


2 Answers

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.

like image 67
Steve Haley Avatar answered Nov 06 '22 00:11

Steve Haley


Steve, Google has a great article and tutorial for handling UI Events @ http://developer.android.com/guide/topics/ui/ui-events.html. This is what got me started and it was great for me :-)

like image 29
Seaux Avatar answered Nov 05 '22 22:11

Seaux