Android image view matrix scale + translate(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图像视图矩阵缩放+翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android图像视图矩阵缩放+翻译
基础教程推荐
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01