本教程将介绍如何在Android中进行缩放、旋转和平移操作后获得相对于父对象的视图位置?的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。
问题描述
我正在开发一项功能,其中包括图像缩放、旋转和平移操作。所有这些操作对我来说都运行良好。
现在,我需要检查相对于父级的视图位置。我开发了以下代码来获取缩放和平移后的视图位置。
private fun findViewPosition(view: View) {
val left = view.left.toFloat()
val top = view.top.toFloat()
val px = view.pivotX
val py = view.pivotY
val tx = view.translationX
val ty = view.translationY
val sx = view.scaleX
val sy = view.scaleY
val rx = view.rotationX
val ry = view.rotationY
val r = view.rotation
// Getting correct value for startX and startY after scale and translate.
// After the rotation, I'm not sure how to applied the formula.
val startX = left - (view.width * sx - view.width) / 2 + tx
val startY = top - (view.height * sy - view.height) / 2 + ty
Log.w("Start", "$startX , $startY")
val endX = left + view.width + (view.width * sx - view.width) / 2 + tx
val endY = top + view.height + (view.height * sy - view.height) / 2 + ty
Log.w("End","$endX , $endY")
}
旋转视图后,我在查找位置时遇到困难。如果有人能在这方面帮我,那将对我有很大帮助。
如果您想试用代码,以下是示例代码:AndroidViewScaleRotateTranslate.zip
谢谢!
推荐答案
您可能需要使用视图的旋转值手动计算位置。
请记住,实际视图不旋转,只旋转内容。可以这样表示(红色=旋转,蓝色=实际视图):
A:视图居中。
B:实际视图的左上角Rect
。
C:视图左上边缘旋转。
?(Alpha):AB和AC之间的角度。
我们有A、B和?。我们想知道C。因此,使用三角函数,我们得到this formula:
使用下列值(假设B为坐标原点):
A:(ax=view.getWidth()/2)(Ay=view.getHeight()/2)
B:(bx=0),(by=0)
?(Alpha):(?=view.getRotation())
由于B始终为0,我们可以简化:
?? = ?? - (??)cos? + (??)sin?
?? = ?? - (??)sin? - (??)cos?
代码应如下所示:
float aX = view.getWidth() / 2.f;
float aY = view.getHeight() / 2.f;
float alpha = Math.toRadians(view.getRotation());
float sin = Math.sin(alpha);
float cos = Math.cos(alpha);
float cX = aX - aX * cos + aY * sin;
float cY = aY - aX * sin - aY * cos;
如果您现在想要相对于父级的职位:
float relX = view.getX() + cX;
float relY = view.getY() + cY;
这就是您要找的职位。
好了关于怎么在Android中进行缩放、旋转和平移操作后获得相对于父对象的视图位置?的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。