【UGUI】計算UGUI層級較深的物體在屏幕上的座標

計算屏幕座標一般狀況是比較容易的事情,可是一但UI層級比較深,父物體的錨點自定義較多,一會左上角,一會右下角…這個時候計算層級最深的UI物體的屏幕座標是一件至關困難的事情…
Unity官方的API裏面提供了一個這樣的方法,我下面的註釋和我當前需求有關,你們能夠忽略參數2的描述,參數2就是你想轉換的層級比較深的UI的位置web

這一段代碼,計算獲得的座標,就是UI中心點的座標,意思就是不管UI使用了哪一種錨點,該方法計算的位置都是認爲UI的錨點在對角線交叉點canvas

Vector2 pos;
        // 計算中心點座標(不管UI使用哪一種錨點都將其看作是錨點在中心點)
        // 參數1:canvas
        // 參數2:想要限制的UI區域的物體位置
        // 參數3:UI攝像機
        // 參數4:輸出的結果嗎
        // 注意:轉換的時候,參數2物體的Z必須爲0
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform,m_mapRect.position,canvas.GetComponent<Camera>(),out pos)) {
            Debug.LogError ("轉換pos:"+pos);  
        }

計算上下左右4個邊的位置svg

//just suitable for the condition witch Anchor at Image center
        // 左
        float minX = Screen.width/2 + m_mapRect.localPosition.x - m_mapRect.rect.width/2.0f;
        // 右
        float maxX = Screen.width/2 + m_mapRect.localPosition.x + m_mapRect.rect.width/2.0f;
        // 上
    float minY = Screen.height/2 - m_mapRect.localPosition.y - m_mapRect.rect.height/2.0f;
        // 下
        float maxY = Screen.height/2 - m_mapRect.localPosition.y + m_mapRect.rect.height/2.0f;