我正在开发一个可以旋转很多 View 的应用程序 - 它有点像物理对象的 map 。我必须检测 2 个对象(所有对象都是矩形/正方形)何时重叠,以及用户是否对对象执行了单击/双击/长按。出于这个原因,我需要知道 View 的绘图边界。
让我们看看下面的示例图像 - 绿色矩形旋转了 45 度。我需要获取绿色矩形的 4 个角的坐标。如果我使用 view.getHitRect() 它返回 View 的边界框(标记为红色),这对我没有用。
你知道我怎样才能得到 View 边缘的坐标吗?
我能想到的唯一解决方案是将 View 子类化,手动存储角的初始坐标,并在每次对 View 进行修改时计算它们的新值——平移、缩放和旋转,但我想知道是否有更好的方法方法。
附言该应用程序应在 Android 2.3 上运行,但也欢迎 4.0+ 解决方案。
最佳答案
感谢 pskink,我再次探索了 Matrix.mapPoints 方法并设法获得了矩形角的正确坐标。
如果您在 Android 3.0+ 上运行,您可以通过调用 myView.getMatrix() 轻松获取 View 的矩阵并映射兴趣点。我必须对左上角使用 0,0,对右下角使用 getWidth()、getHeight(),并将这些坐标映射到矩阵。之后添加 View 的 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 .然后我复制并修改了其中一个内部方法来获取 View 的矩阵:
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;
}
我已将此方法放在 View 的重载类中(在我的例子中 - 扩展 TextView)。从那里开始,它与 Android 3.0+ 中的相同,但不是调用 myView.getMatrix(),而是调用 myView.getViewMatrix()。
关于android - 获取 View 的绘制边界/矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22605605/