简体   繁体   English

Android画布中位图的同时旋转,平移和缩放

[英]Simultaneous rotation, translation, and scaling of bitmap in android canvas

I'm trying to show a picture, which can be zoomed and panned, and that rotates with a compass reading. 我正在尝试显示一张可以缩放和平移的图片,并使用指南针读取旋转。 With the code below, all three actions kind of work, but they influence each other. 使用下面的代码,所有三种操作都有效,但它们相互影响。

Here is what I want to achieve: 这是我想要实现的目标:
1. Rotate around the center of the screen 1.围绕屏幕中心旋转
2. Scale leaving the same part of the picture in the center 2.缩放将图片的相同部分留在中心
3. Pan to the desired spot in the picture 3.平移到图片中的所需位置

Here is what is actually happening with the code below: 以下是代码实际发生的情况:
1. Rotation works as intended, around the center of the screen 1.旋转按预期工作,围绕屏幕中心
2. Scaling works, but it scales around the center of the picture 2.缩放工作,但它围绕图片中心缩放
3. Translation only works as intended if angle is zero, otherwise it's moving in a wrong direction 3.如果angle为零,则只能按预期进行平移,否则它将向错误的方向移动

// the center of the view port
float centerX = screen.right/2;
float centerY = screen.bottom/2;

Matrix m = new Matrix();
m.preRotate(angle, centerX, centerY);
m.preScale(mScaleFactor, mScaleFactor, centerX, centerY);

// scaling the amount of translation, 
// rotating the translation here gave crazy results
float x = mPosX / mScaleFactor;
float y = mPosY / mScaleFactor;
m.preTranslate(x, y);

canvas.drawBitmap(pic, m, null);

If I translate first, and later rotate, the translation works as intended but the rotation is not around the center of the view port anymore. 如果我先翻译,然后再旋转,则翻译按预期工作,但旋转不再围绕视口的中心。

How can I apply all three transformations, without them influencing each other? 如何在不相互影响的情况下应用所有三种变换?

I'm not sure about the scaling around the centre of the image, but as for the translation being in the wrong direction is it not as a consequence of you rotating the image but not the translations? 我不确定图像中心周围的缩放比例,但是因为旋转图像而不是翻译,翻译的方向是错误的吗? Maybe try something like this: 也许尝试这样的事情:

float x = (mPosX*(cos(angle) + sin(angle)) / mScaleFactor;
float y = (mPosY*(cos(angle) - sin(angle)) / mScaleFactor;
m.preTranslate(x, y);

Also does the matrix object have a method to apply an affine transformation directly? 矩阵对象也有一种直接应用仿射变换的方法吗? Because then you won't need to think about the order of operations. 因为那时你不需要考虑操作的顺序。

The affine transformation might look something like this: 仿射变换可能看起来像这样:

M = |mScaleFactor*cos(angle)       sin(angle)            x|
    |     -sin(angle)          mScaleFactor*cos(angle)   y|
    |          0                         0               1|

But this will rotate around the corner of the image so you need to use the preTranslate() function first like so: 但是这将围绕图像的角旋转,因此您需要首先使用preTranslate()函数,如下所示:

Mt.preTranslate(-centerX,-centerY);

And APPLY Mt to pic before applying M and then after you need to apply -Mt 并且在应用M之前将Mt应用于pic,然后在需要应用-Mt之后

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM