ImageView Drag Limitation In Android

前端 未结 5 1650
遇见更好的自我
遇见更好的自我 2021-02-09 06:21

I have an ImageView in a layout and set OnTouchListener on ImageView to drag the ImageView. It\'s working perfectly. My problem is how can I prevent from move ImageView to out o

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-09 06:51

    1. We need to create two Rect objects, one is for our view and another for our image according to the view coordinates.

      float[] values = new float[9];
      matrix.getValues(values);
      float globalX = values[Matrix.MTRANS_X];
      float globalY = values[Matrix.MTRANS_Y];
      float scaleX = values[Matrix.MSCALE_X];
      float scaleY = values[Matrix.MSCALE_Y];
      Rect viewRect = new Rect(0, 0, viewWidth, viewHeight);
      Rect imageRect = new Rect((int) globalX, (int) globalY, Math.round(bitmapWidth * scaleX + globalX),
              Math.round(bitmapHeight * scaleY + globalY));
      
      1. If we want our image be always inside our view, then we check this:

        if (!viewRect.contains(imageRect)) {
            matrix.set(lastSetMatrix); //return to last saved parameters
        }
        
      2. Sometimes we need our image always be bigger than our view to position a part of the image inside the view, then we can check this:

        if (!imageRect.contains(viewRect)) {
           matrix.set(lastSetMatrix);
        }
        

提交回复
热议问题