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)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…