Android图像视图矩阵缩放+翻译 [英] Android image view matrix scale + translate

查看:36
本文介绍了Android图像视图矩阵缩放+翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试手动获取图像视图中的图像,使其居中并适合屏幕.我需要用矩阵来做(我稍后会动态改变矩阵变换).

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;

我有一些价值观:- 图像:200x133- 显示:800x480- minScale:2.4- 图片的最后一个左上角:100, 67(应该是 17, 0)

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

推荐答案

有一个方便的方法叫做 Matrix.setRectToRect(RectF, RectF, ScaleToFit) 来帮你.p>

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

这应该将矩阵 m 设置为具有缩放和转换值的组合,以显示可绘制居中并适合 ImageView 小部件.

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.

这篇关于Android图像视图矩阵缩放+翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆