Detect touch on bitmap

前端 未结 3 1335
温柔的废话
温柔的废话 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:57

    This will detect a touch and check if it is not transparent. You need this if your bitmaps are not rectangles. myBitmap is just a simple container class I use.

    private boolean clickOnBitmap(MyBitmap myBitmap, MotionEvent event) {
        float xEnd = myBitmap.originX() + myBitmap.width();
        float yEnd = myBitmap.originY() + myBitmap.height();;
    
    
        if ((event.getX() >= myBitmap.originX() && event.getX() <= xEnd) 
        && (event.getY() >= myBitmap.originY() && event.getY() <= yEnd) ) {
            int pixX = (int) (event.getX() - myBitmap.originX());
            int pixY = (int) (event.getY() - myBitmap.originY());
            if (!(myBitmap.getBitmap().getPixel(pixX, pixY) == 0)) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }
    

    This is the on touch code for completeness

        @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (clickOnBitmap(dog, event)) {
                    Toast.makeText(getContext(), "dog", Toast.LENGTH_SHORT).show();
                } else if (clickOnBitmap(mouse,event)) {
                    Toast.makeText(getContext(), "mouse", Toast.LENGTH_SHORT).show();
                }
            return true;
            case MotionEvent.ACTION_OUTSIDE:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                return true;
        }
        return false;
    }  
    

提交回复
热议问题