Detect touch on bitmap

前端 未结 3 1334
温柔的废话
温柔的废话 2020-11-29 06:03

Greets,

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

Thanks

3条回答
  •  隐瞒了意图╮
    2020-11-29 06:54

    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.

提交回复
热议问题