简体   繁体   English

比例尺后的Android Bitmap / Canvas偏移量

[英]Android Bitmap/Canvas offset after scale

If I have a canvas, on which I draw a Bitmap like this: 如果我有一个画布,我在上面绘制一个像这样的Bitmap:

canvas.drawBitmap(bmLargeImage, srcRect, destRect, paint);

and I scale the bitmap: 我缩放位图:

canvas.scale(1.5f, 1.5f, 450, 250);

I want to get the position of the Bitmap after the scale. 我希望在比例后获得位图的位置。 If the position before scale was (0, 0), after scale there is a offset and I need that offset.. how can I get it? 如果比例前的位置是(0,0),那么在比例之后有一个偏移,我需要那个偏移..我怎么能得到它?

Thanks and sorry for the simple question, newbie here... 谢谢,抱歉这个简单的问题,新手在这里......

Ok lets try to work out the best formula for this 好吧,让我们尝试找出最好的配方

canvas.scale(scaleX, scaleY, pivotX, pivotY);  

if (scaleX >= 1){    
  objectNewX = objectOldX + (objectOldX - pivotX)*(scaleX - 1); 
}else{   
  objectNewX = objectOldX - (objectOldX - pivotX)*(1 - scaleX); 
}

The same for objectNewY. 对于objectNewY也是如此。 The new width and height of the bitmap would of course be the multiple of the old size and scale. 位图的新宽度和高度当然是旧尺寸和比例的倍数。

I believe the cleanest Solution would be to use the underlying transformation Matrix of the Canvas you are manipulating. 我相信最干净的解决方案是使用您正在操作的Canvas底层转换矩阵。

In Android there is the canvas.getMatrix(Matrix cmt) method available which will yield it. 在Android中,有canvas.getMatrix(Matrix cmt)方法可用,它将产生它。 The transformation matrix will transform any point in world space you throw at into screen coordinates. 变换矩阵将您投射的世界空间中的任何点变换为屏幕坐标。 Just use the matrix.mapPoints(float[] points) and you will be fine. 只需使用matrix.mapPoints(float[] points)就可以了。

FYI, you can easily do it the other way around too. 仅供参考,您也可以通过其他方式轻松完成。 If you want to know what screen coordinate maps to which point in world space, eg for tapping; 如果您想知道哪个屏幕坐标映射到世界空间中的哪个点,例如用于点击; the inverse matrix can be used for that. 逆矩阵可以用于此。 It can be obtained via the matrix.invert(Matrix out) method. 它可以通过matrix.invert(Matrix out)方法获得。 Use its mapPoints() for the coordinate mapping then. 然后使用其mapPoints()进行坐标映射。

Here are the official docs: mapPoints() , invert() , getMatrix() 以下是官方文档: mapPoints()invert()getMatrix()

If you'd like know the corners of your screen relative to your original canvas, you can use canvas.getClipBounds() . 如果您想知道屏幕相对于原始画布的角落,可以使用canvas.getClipBounds() This returns a Rect with edge coordinates relative to your original canvas. 这将返回一个Rect ,其边缘坐标相对于原始画布。 For instance, if you start off with a canvas size of 320 x 480 and call 例如,如果你开始使用320 x 480的画布尺寸并打电话

canvas.scale(2, 2, getWidth()/2, getHeight()/2);

and then 然后

canvas.getClipBounds();

you will have a Rect (call this rect ) where 你将有一个Rect (称之为rect )在哪里

rect.top == 120
rect.bottom == 360
rect.left == 80
rect.right == 240

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

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