我正在尝试手动获取以图像视图为中心并适合屏幕的图像。我需要用矩阵来完成(稍后我将动态更改矩阵变换)。
问题是我无法使图像在视图中居中(比例合适)。这是代码:
// 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);
如果我不将比例放在图像中心的中心,上面的代码就可以工作(但我稍后需要这样做,所以我现在需要弄清楚公式)。
我认为执行以下操作可以解决问题,但图像仍然偏移(朝底部和右侧)。
tx += 0.5*imageWidth*minScale;
ty += 0.5*imageHeight*minScale;
我有一些价值观:
- 图片:200x133
- 显示:800x480
- 最小规模:2.4
- 图像的最终左上角:100, 67(应为 17, 0)