title: Android image view matrix scale + translate
body: <p>I am trying to manually get an image inside an imageview centered and fitting the screen. I need to do it with a matrix (I will later dynamically change the matrix transformation). </p>
  
  <p>Problem is I can't get the image centered in the view (scale is appropriate). Here is the code:</p>
  
  <pre><code>// Compute the scale to choose (this works)
  float scaleX = (float) displayWidth / (float) imageWidth;
  float scaleY = (float) displayHeight / (float) imageHeight;
  float minScale = Math.min(scaleX, scaleY);
  
  // tx, ty should be the translation to take the image back to the screen center
  float tx = Math.max(0, 
          0.5f * ((float) displayWidth - (minScale * imageWidth)));
  float ty = Math.max(0, 
          0.5f * ((float) displayHeight - (minScale * imageHeight)));
  
  // Compute the matrix
  Matrix m = new Matrix();
  m.reset();
  
  // Middle of the image should be the scale pivot
  m.postScale(minScale, imageWidth/2, imageHeight/2);
  
  // Translate
  m.postTranslate(tx, ty);
  
  imageView.setImageMatrix(m);
  </code></pre>
  
  <p>The above code works if I don't center the scale on the image center (but I will need to do it later so I need to figure out the formula now).</p>
  
  <p>I thought doing the following would correct the issue, but the image is still offset (towards bottom and right).</p>
  
  <pre><code>tx += 0.5*imageWidth*minScale;
  ty += 0.5*imageHeight*minScale;
  </code></pre>
  
  <p>Some values I have: 
  - image: 200x133
  - display: 800x480
  - minScale: 2.4
  - final top-left corner of the image: 100, 67 (should be 17, 0)</p>