簡體   English   中英

獲取視圖的邊界/矩形

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM