How to keep an image inside the screen limits while using pinch zoom and drag gestures?

后端 未结 2 1243
死守一世寂寞
死守一世寂寞 2021-02-09 21:53

I\'m building an app that uses the pinch zoom and drag. The problem is that for now I can drag the picture out of it bounds. I wanted to know how can I use drag and make sure th

2条回答
  •  我寻月下人不归
    2021-02-09 22:35

    public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
    
            DisplayMetrics displaymetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
            int sH = displaymetrics.heightPixels;
            int sW = displaymetrics.widthPixels;
            float dx, dy, newX, newY;
    
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    dx = event.getRawX() - v.getX();
                    dy = event.getRawY() - v.getY();
                    break;
    
                case MotionEvent.ACTION_MOVE:
                    newX = event.getRawX() - dx;
                    newY = event.getRawY() - dy;
    
                    if ((newX <= 0 || newX >= sW-v.getWidth()) || (newY <= 0 || newY >= sH-v.getHeight()))
                        break;
    
                    v.setX(newX);
                    v.setY(newY);
                    break;   
    
                default:
                    break;
            }
    
            return true;
        }
    

提交回复
热议问题