感谢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);
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()。