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

社会主义新天地 提交于 2019-12-03 07:32:41

Why not grab the dimensions of the screen and check the MotionEvent coordinates are within these before updating your matrix?

Something like..

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int screenHight = displaymetrics.heightPixels;
int screenWidth = displaymetrics.widthPixels;

   ...
   case MotionEvent.ACTION_MOVE:

      if (mode == DRAG) {

         int newX = event.getX() - start.x;
         int newY = event.getY() - start.y;
         if ( (newX <= 0 || newX >= screenWidth) ||
              (newY <= 0 || newY >= screenHeight) )
             break;

         matrix.set(savedMatrix);
         matrix.postTranslate(newX, newY);
      }
   ...
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;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!