Android的图像显示矩阵规模+翻译 [英] Android image view matrix scale + translate

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

问题描述

我试图手动得到中心的ImageView的内部图像,并配合屏幕。我需要用一个矩阵做到这一点(我将在稍后动态地改变矩阵变换)。

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

问题是我不能集中在视图(比例合适)的图像。这里是code:

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

以上code的作品,如果我不居中规模上的图像中心(但我需要做它以后,所以我现在需要弄清楚的公式)。

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)

推荐答案

有一个简便的方法称为<一个href="http://developer.android.com/reference/android/graphics/Matrix.html#setRectToRect%28android.graphics.RectF,%20android.graphics.RectF,%20android.graphics.Matrix.ScaleToFit%29">Matrix.setRectToRect(RectF, RectF,ScaleToFit),以帮助你在这里。

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天全站免登陆