Android image view matrix scale + translate

Vincent Mimoun-Prat picture Vincent Mimoun-Prat · May 20, 2011 · Viewed 91.5k times · Source

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).

Problem is I can't get the image centered in the view (scale is appropriate). Here is the 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);

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).

I thought doing the following would correct the issue, but the image is still offset (towards bottom and right).

tx += 0.5*imageWidth*minScale;
ty += 0.5*imageHeight*minScale;

Some values I have: - image: 200x133 - display: 800x480 - minScale: 2.4 - final top-left corner of the image: 100, 67 (should be 17, 0)

Answer

Joakim Erdfelt picture Joakim Erdfelt · May 30, 2011

There's a convenient method called Matrix.setRectToRect(RectF, RectF, ScaleToFit) to help you here.

Matrix m = imageView.getImageMatrix();
RectF drawableRect = new RectF(0, 0, imageWidth, imageHeight);
RectF viewRect = new RectF(0, 0, imageView.getWidth(), imageView.getHeight());
m.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER);
imageView.setImageMatrix(m);

That should set the matrix m to have combo of scaling and translate values that is needed to show the drawable centered and fit within the ImageView widget.