[英]Get draw bounds/rect of a view
我正在开发一个可以旋转许多视图的应用程序-有点像物理对象的地图。 我必须检测2个对象(所有对象均为矩形/正方形)何时重叠以及用户是否对某个对象执行了单次/双击/长按。 因此,我需要知道视图的绘图范围。
让我们看下面的示例图像-绿色矩形旋转了45度。 我需要获取绿色矩形的4个角的坐标。 如果我使用view.getHitRect(),它将返回视图的边界框(标记为红色),这对我没有用。
您知道如何获取视图边缘的坐标吗?
我能想到的唯一解决方案是对View进行子类化,手动存储拐角的初始坐标,并在对视图的每次修改(平移,缩放和旋转)上计算其新值,但我想知道是否有更好的方法。
PS该应用程序应可在Android 2.3上运行,但也欢迎4.0+解决方案。
多亏了pskink,我再次探索了Matrix.mapPoints方法,并设法获得了矩形角的正确坐标。
如果您在Android 3.0+上运行,则可以通过调用myView.getMatrix()并映射兴趣点来轻松获取视图的矩阵。 我必须对左上角使用0,0,对右下角使用getWidth(),getHeight()并将这些坐标映射到矩阵。 之后,添加视图的X和Y值以获取角的真实值。
就像是:
float points[] = new float[2];
points[0] = myView.getWidth();
points[1] = myView.getHeight();
myView.getViewMatrix().mapPoints(points);
Paint p = new Paint();
p.setColor(Color.RED);
//offset the point and draw it on the screen
canvas.drawCircle(center.getX() + points[0], center.getY() + points[1], 5f, p);
如果必须支持较低版本的Android,则可以使用NineOldAndroids 。 然后,我复制并修改了其内部方法之一,以获取视图的矩阵:
public Matrix getViewMatrix()
{
Matrix m = new Matrix();
Camera mCamera = new Camera();
final float w = this.getWidth();
final float h = this.getHeight();
final float pX = ViewHelper.getPivotX(this);
final float pY = ViewHelper.getPivotY(this);
final float rX = ViewHelper.getRotationX(this);;
final float rY = ViewHelper.getRotationY(this);
final float rZ = ViewHelper.getRotation(this);
if ((rX != 0) || (rY != 0) || (rZ != 0))
{
final Camera camera = mCamera;
camera.save();
camera.rotateX(rX);
camera.rotateY(rY);
camera.rotateZ(-rZ);
camera.getMatrix(m);
camera.restore();
m.preTranslate(-pX, -pY);
m.postTranslate(pX, pY);
}
final float sX = ViewHelper.getScaleX(this);
final float sY = ViewHelper.getScaleY(this);;
if ((sX != 1.0f) || (sY != 1.0f)) {
m.postScale(sX, sY);
final float sPX = -(pX / w) * ((sX * w) - w);
final float sPY = -(pY / h) * ((sY * h) - h);
m.postTranslate(sPX, sPY);
}
m.postTranslate(ViewHelper.getTranslationX(this), ViewHelper.getTranslationY(this));
return m;
}
我已经将此方法放在视图的重载类中(在我的情况下是扩展TextView)。 从那里开始,它与Android 3.0+中的相同,但是不调用myView.getMatrix(),而是调用myView.getViewMatrix()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.