title: How to limit image pan boundary in Android imageView
body: <p>I have an imageView with multitouch roughly based on <a href="http://www.zdnet.com/blog/burnette/how-to-use-multi-touch-in-android-2-part-6-implementing-the-pinch-zoom-gesture/1847" rel="nofollow">this tutorial</a>. One of the commenters there put together a semi-dirty method of limiting the image drag to the boundaries of the image, so that the image edge cannot be dragged beyond its edge. This method sorta works, but not entirely. It only limits drag of two edges.</p>
  
  <p>Does anyone know a less messy and actually functional method for limiting image drag?</p>
  
  <p>This is a highly important concept for android app development that is not adequately addressed....</p>
  
  <p>I was thinking of the following ideas:</p>
  
  <p>1) setScaleType(scaleType.fitXY) when zoom = 1.0F (i.e. min zoom), and drag only enabled when zoom > 1.0f</p>
  
  <p>2) when zoom > 1.0f, setScaleType(scaleType.MATRIX), then you determine image bounds and screen dimensions, and in some way that is too smart for me, using an if statement you only allow drag when the image edge is not on the screen. I don't know how to declare that, is the thing. </p>
  
  <p>anyways, for completeness, here is the limit pan code from that link. This seems to be the most popular suggestion on stackoverflow, but I think we can do better:</p>
  
  <pre><code>// limit pan
  matrix.getValues(matrixValues);
  float currentY = matrixValues[Matrix.MTRANS_Y];
  float currentX = matrixValues[Matrix.MTRANS_X];
  float currentScale = matrixValues[Matrix.MSCALE_X];
  float currentHeight = height * currentScale;
  float currentWidth = width * currentScale;
  float dx = event.getX() - start.x;
  float dy = event.getY() - start.y;
  float newX = currentX+dx;
  float newY = currentY+dy; 
  
  RectF drawingRect = new RectF(newX, newY, newX+currentWidth, newY+currentHeight);
  float diffUp = Math.min(viewRect.bottom-drawingRect.bottom, viewRect.top-drawingRect.top);
  float diffDown = Math.max(viewRect.bottom-drawingRect.bottom, viewRect.top-drawingRect.top);
  float diffLeft = Math.min(viewRect.left-drawingRect.left, viewRect.right-drawingRect.right);
  float diffRight = Math.max(viewRect.left-drawingRect.left, viewRect.right-drawingRect.right);
  if(diffUp &gt; 0 ){
  dy +=diffUp; 
  }
  if(diffDown &lt; 0){
  dy +=diffDown;
  } 
  if( diffLeft&gt; 0){ 
  dx += diffLeft;
  }
  if(diffRight &lt; 0){
  dx += diffRight;
  }
  matrix.postTranslate(dx, dy);
  </code></pre>